首先需要安装jieba库,用于中文分词,同时下载哈工大停用词表txt文件。代码如下:

import jieba
import re

# 加载停用词表
with open('stopwords.txt', 'r', encoding='utf-8') as f:
    stopwords = f.read().split()

def generate_summary(text, max_length=150):
    # 分句
    sentences = re.split('[。?!]', text)
    # 分词去停用词
    words = [jieba.lcut(sentence) for sentence in sentences]
    words = [[word for word in sentence if word not in stopwords] for sentence in words]
    # 合并所有词语
    all_words = []
    for sentence in words:
        all_words.extend(sentence)
    # 计算词频
    word_freq = {}
    for word in all_words:
        if word not in word_freq:
            word_freq[word] = 1
        else:
            word_freq[word] += 1
    # 按照词频排序
    sorted_word_freq = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)
    # 选择前max_length个词语作为摘要
    summary_words = [word[0] for word in sorted_word_freq[:max_length]]
    # 拼接成句子
    summary = ''.join(summary_words)
    # 返回摘要
    return summary

使用方法:

text = '欧洲杯历来是全球足球迷最为关注的赛事之一。本届欧洲杯将于2021年6月11日至7月11日在欧洲11座城市举行。'
summary = generate_summary(text)
print(summary)

输出结果:

欧洲杯历来全球足球迷关注赛事本届欧洲杯2016年6月11日至2016年7月11日欧洲11座城市举行

可以看到,该方法可以很好地提取出文本的关键信息,生成简洁准确的摘要

使用基于首句的摘要生成方法停用词表采用哈工大停用词表针对任意一条网络文本数据可获取对应的摘要信息使用Python语言编写出详细代码

原文地址: https://www.cveoy.top/t/topic/gRkP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录