本文目录导读:
我来详细说明如何使用textrank4zh库抽取中文文章的关键句子。
安装textrank4zh
pip install textrank4zh
基本使用方法
1 最简单的示例
from textrank4zh import TextRank4Sentence
# 初始化
tr4s = TextRank4Sentence()
# 待分析的文本
text = """
人工智能(Artificial Intelligence,简称AI)是计算机科学的一个分支,它试图理解智能的实质,并生产出一种新的能以人类智能相似的方式做出反应的智能机器。
近年来,随着深度学习技术的突破,人工智能在图像识别、自然语言处理、语音识别等领域取得了显著进展。
特别是在自然语言处理领域,BERT、GPT等预训练模型的出现,极大地推动了机器理解人类语言的能力。
人工智能的发展也引发了一些担忧,比如就业岗位的替代、隐私保护等问题。
人工智能技术正在深刻改变着我们的生活方式和工作方式。
"""
# 分析文本
tr4s.analyze(text=text, lower=False, source='all_filters')
# 提取关键句子(默认返回4个)
key_sentences = tr4s.get_key_sentences(num=3)
# 打印结果
for sentence in key_sentences:
print(f"句子:{sentence.sentence}")
print(f"权重:{sentence.weight:.4f}")
print("---")
2 详细参数配置
from textrank4zh import TextRank4Sentence
import jieba
class ChineseTextSummarizer:
def __init__(self):
self.tr4s = TextRank4Sentence()
def extract_key_sentences(self, text, num=3):
"""
提取关键句子
Args:
text: 中文文本
num: 返回的句子数量
"""
# 分析文本
# source参数:'all_filters'(默认), 'no_stop_words', 'no_tags'
# lower参数:是否转换为小写,中文设为False
self.tr4s.analyze(
text=text,
lower=False, # 中文不需要小写
source='all_filters', # 使用所有过滤选项
sim_func=self.compute_similarity # 自定义相似度函数(可选)
)
# 提取关键句子
sentences = self.tr4s.get_key_sentences(
num=num, # 返回句子数量
sentence_min_len=6 # 最小句子长度(字符数)
)
return sentences
def compute_similarity(self, sent1, sent2):
"""自定义句子相似度计算"""
# 简单实现:基于词重叠
words1 = set(jieba.cut(sent1))
words2 = set(jieba.cut(sent2))
if not words1 or not words2:
return 0
intersection = words1 & words2
union = words1 | words2
return len(intersection) / len(union)
# 使用示例
summarizer = ChineseTextSummarizer()
text = "你的长文本..."
key_sentences = summarizer.extract_key_sentences(text, num=5)
实际应用示例
1 新闻摘要提取
def extract_news_summary(news_text, num_sentences=3):
"""
从新闻中提取摘要
Args:
news_text: 新闻文本
num_sentences: 摘要句子数
Returns:
摘要文本
"""
tr4s = TextRank4Sentence()
tr4s.analyze(text=news_text, lower=False)
# 提取关键句子
key_sentences = tr4s.get_key_sentences(num=num_sentences)
# 按原文顺序排序
sorted_sentences = sorted(key_sentences, key=lambda x: x.index)
# 组合成摘要
summary = ' '.join([sent.sentence for sent in sorted_sentences])
return summary
# 示例
news = """
2024年人工智能发展迎来重大突破,OpenAI发布了GPT-5模型,其性能在多项基准测试中超越了人类水平。
谷歌、微软等科技巨头也在AI领域投入巨资,加速技术迭代。
国内方面,百度、华为等企业积极布局,推动AI与产业深度融合。
专家预测,未来五年人工智能将深刻改变医疗、教育、金融等多个行业格局。
AI技术的发展也带来了数据安全、隐私保护等新挑战。
各国政府正在加快制定相关法律法规,以确保AI技术健康发展。
"""
summary = extract_news_summary(news, num_sentences=2)
print("新闻摘要:")
print(summary)
2 长文档摘要
def extract_document_summary(document_path):
"""
从长文档中提取摘要
Args:
document_path: 文档路径
Returns:
摘要结果
"""
# 读取文档
with open(document_path, 'r', encoding='utf-8') as f:
text = f.read()
tr4s = TextRank4Sentence()
# 分块处理长文本
chunk_size = 20000 # 每块字符数
chunks = [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
all_sentences = []
for chunk in chunks:
# 分析每个分块
tr4s.analyze(text=chunk, lower=False)
# 提取每个分块的关键句子
chunk_sentences = tr4s.get_key_sentences(num=5)
all_sentences.extend(chunk_sentences)
# 按权重排序
all_sentences.sort(key=lambda x: x.weight, reverse=True)
# 返回top-N句子
top_sentences = all_sentences[:3]
result = []
for sent in top_sentences:
result.append({
'content': sent.sentence,
'weight': sent.weight,
'position': sent.index
})
return result
# 使用示例
# summary = extract_document_summary('document.txt')
# for item in summary:
# print(f"重要性:{item['weight']:.4f}")
# print(f"内容:{item['content']}")
# print("-" * 50)
高级应用
from textrank4zh import TextRank4Sentence
import jieba.analyse
class AdvancedSummarizer:
def __init__(self):
self.tr4s = TextRank4Sentence()
def extract_with_keywords(self, text, num_sentences=3, num_keywords=5):
"""
结合关键词提取关键句子
Args:
text: 文本
num_sentences: 句子数
num_keywords: 关键词数
"""
# 提取关键词
keywords = jieba.analyse.extract_tags(
text, topK=num_keywords, withWeight=True
)
# 分析句子
self.tr4s.analyze(text=text, lower=False)
sentences = self.tr4s.get_key_sentences(num=num_sentences * 2)
# 结合关键词权重重新排序
scored_sentences = []
for sent in sentences:
keyword_score = sum(
weight for word, weight in keywords
if word in sent.sentence
) / len(keywords)
# 结合TextRank权重和关键词权重
combined_score = 0.7 * sent.weight + 0.3 * keyword_score
scored_sentences.append((sent, combined_score))
# 重新排序
scored_sentences.sort(key=lambda x: x[1], reverse=True)
best_sentences = scored_sentences[:num_sentences]
return [sent for sent, score in best_sentences]
# 使用示例
summarizer = AdvancedSummarizer()
text = "你的文本..."
key_sentences = summarizer.extract_with_keywords(text)
for sent in key_sentences:
print(f"[{sent.weight:.4f}] {sent.sentence}")
性能优化建议
import time
from functools import lru_cache
class OptimizedSummarizer:
def __init__(self):
self.tr4s = TextRank4Sentence()
@lru_cache(maxsize=128)
def cached_extract(self, text_hash):
"""缓存已分析的文本"""
return None # 实际实现需要处理
def extract_summary(self, text, num=3):
"""优化的摘要提取"""
start_time = time.time()
# 预处理:去除多余空白
text = ' '.join(text.split())
# 分析
self.tr4s.analyze(text=text, lower=False)
# 提取
sentences = self.tr4s.get_key_sentences(num=num)
elapsed = time.time() - start_time
print(f"处理时间:{elapsed:.3f}秒")
return sentences
注意事项
- 文本长度:建议处理的文本长度在5000-10000字之间
- 语言要求:输入必须是中文文本
- 预处理:建议先去除HTML标签、特殊字符等
- 结果排序:返回的句子按权重降序排列,不一定按原文顺序
这样你就可以使用textrank4zh库有效地提取中文文章的关键句子了,根据具体需求,可以调整参数和增加后处理逻辑。
标签: TextRank