Python实例题:Python实现英文新闻摘要自动提取

目录

Python实例题

题目

实现思路

代码实现

代码解释

preprocess_text 函数:

extract_summary 函数:

主程序:

运行思路

注意事项

Python实例题

题目

Python实现英文新闻摘要自动提取

实现思路

  • 数据准备:读取英文新闻文本。
  • 文本预处理:使用nltk对新闻文本进行分词、去除停用词等操作。
  • 摘要提取:使用sumy库中的算法提取新闻摘要。
  • 结果输出:输出提取的摘要。

代码实现

import nltk
from sumy.parsers.plaintext import PlaintextParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.summarizers.lex_rank import LexRankSummarizer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import string

# 下载必要的 nltk 数据
nltk.download('punkt')
nltk.download('stopwords')


def preprocess_text(text):
    """
    对新闻文本进行预处理
    :param text: 原始新闻文本
    :return: 预处理后的文本
    """
    # 转换为小写
    text = text.lower()
    # 分词
    tokens = word_tokenize(text)
    # 去除停用词和标点符号
    stop_words = set(stopwords.words('english') + list(string.punctuation))
    filtered_tokens = [token for token in tokens if token not in stop_words]
    # 重新组合成文本
    preprocessed_text = ' '.join(filtered_tokens)
    return preprocessed_text


def extract_summary(text, num_sentences=3):
    """
    提取新闻摘要
    :param text: 新闻文本
    :param num_sentences: 摘要的句子数量,默认为 3
    :return: 提取的摘要
    """
    # 预处理文本
    preprocessed_text = preprocess_text(text)
    # 创建解析器和分词器
    parser = PlaintextParser.from_string(preprocessed_text, Tokenizer('english'))
    # 创建摘要提取器
    summarizer = LexRankSummarizer()
    # 提取摘要
    summary = summarizer(parser.document, num_sentences)
    # 将摘要转换为字符串
    summary_text = ' '.join([str(sentence) for sentence in summary])
    return summary_text


if __name__ == "__main__":
    # 示例新闻文本
    news_text = """
    The United States has seen a significant increase in COVID - 19 cases in recent weeks. Health officials are warning the public to take precautions. 
    Many states are considering re - implementing lockdown measures. 
    Vaccination efforts are ongoing, but the pace has slowed down. 
    The new variants of the virus are causing concern among experts. 
    People are being urged to get vaccinated as soon as possible.
    """
    # 提取摘要
    summary = extract_summary(news_text)
    print("提取的摘要:")
    print(summary)
    

代码解释

  • preprocess_text 函数

    • 将文本转换为小写。
    • 使用word_tokenize进行分词。
    • 去除英文停用词和标点符号。
    • 重新组合分词后的文本。
  • extract_summary 函数

    • 调用preprocess_text函数对文本进行预处理。
    • 使用PlaintextParserTokenizer创建解析器和分词器。
    • 使用LexRankSummarizer作为摘要提取算法。
    • 提取指定数量的句子作为摘要,并将其转换为字符串。
  • 主程序

    • 定义示例新闻文本。
    • 调用extract_summary函数提取摘要。
    • 输出提取的摘要。

运行思路

  • 安装依赖库:确保已经安装了nltksumy库,可以使用以下命令进行安装:
pip install nltk sumy
  • 运行脚本:将上述代码保存为news_summary_extraction.py文件,在终端中运行:
python news_summary_extraction.py
  • 查看结果:脚本运行后,会输出提取的新闻摘要。

注意事项

  • 数据质量:新闻文本的质量会影响摘要提取的效果,尽量使用格式规范、无明显错误的文本。
  • 摘要算法选择LexRank是一种基于图的摘要提取算法,sumy库还提供了其他算法,如TextRankSummarizer等,可以根据实际需求选择合适的算法。
  • 摘要长度:可以通过修改num_sentences参数来调整摘要的句子数量。

你可能感兴趣的:(实例,python,开发语言)