python作业4:编写程序,统计两会政府工作报告热词频率,并生成词云

​
import jieba
import re
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

# 设置中文显示
plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]
plt.rcParams["axes.unicode_minus"] = False  # 解决负号显示问题


def load_text(file_path):
    """读取文本文件内容"""
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            return file.read()
    except FileNotFoundError:
        print(f"错误:文件 '{file_path}' 不存在")
        return ""
    except Exception as e:
        print(f"错误:读取文件时发生异常: {e}")
        return ""


def preprocess_text(text):
    """预处理文本:去除特殊字符,仅保留中文"""
    return re.sub(r'[^\u4e00-\u9fa5]', ' ', text)


def tokenize_text(text, stopwords=None):
    """分词并去除停用词"""
    if stopwords is None:
        stopwords = set()

    # 使用 jieba 进行分词
    words = jieba.cut(text)

    # 过滤停用词和单个字符
    return [word for word in words if word not in stopwords and len(word) > 1]


def count_words(words, top_n=50):
    """统计词频并返回前 top_n 个词"""
    word_counts = Counter(words)
    return word_counts.most_common(top_n)


def generate_wordcloud(word_counts, mask_image=None, output_file=None):
    """生成词云图"""
    # 如果提供了掩码图像,则使用它
    mask = None
    if mask_image:
        try:
            mask = np.array(Image.open(mask_image))
        except Exception as e:
            print(f"警告:无法加载掩码图像: {e}")

    # 创建词云对象
    wc = WordCloud(
        font_path='simhei.ttf',  # 确保系统中有该字体,否则需要指定具体路径
        width=800,
        height=600,
        background_color='white',
        max_words=200,
        mask=mask,
        contour_width=1,
        contour_color='steelblue'
    )

    # 从词频生成词云
    wc.generate_from_frequencies(dict(word_counts))

    # 显示词云图
    plt.figure(figsize=(10, 8))
    plt.imshow(wc, interpolation='bilinear')
    plt.axis('off')
    plt.title('两会政府工作报告热词分析')

    # 保存词云图(如果指定了输出文件)
    if output_file:
        try:
            wc.to_file(output_file)
            print(f"词云图已保存至: {output_file}")
        except Exception as e:
            print(f"警告:无法保存词云图: {e}")

    plt.show()


def get_default_stopwords():
    """获取默认停用词列表"""
    return set(['的', '了', '和', '是', '在', '要', '我们', '有', '这个', '上',
                '着', '个', '到', '说', '就', '去', '也', '把', '得', '看', '好',
                '自己', '这', '那', '为', '等', '对', '以', '不', '人', '都', '一',
                '一个', '没有', '你', '会', '年', '上', '下', '而', '后', '来', '多',
                '再', '她', '过', '天', '吗', '之', '如', '还', '很', '又', '可', '些',
                '用', '那', '行', '学', '所', '开', '然', '前', '自', '其', '些', '现',
                '此', '但', '却', '从', '乃', '对于', '关于', '通过', '作为'])


def main():
    """主函数:执行整个分析流程"""
    # 用户输入文件路径
    file_path = input("请输入政府工作报告文本文件路径(默认为 'gov_report.txt'):") or 'gov_report.txt'

    # 加载文本
    text = load_text(file_path)
    if not text:
        print("没有文本内容可供分析,程序退出。")
        return

    # 预处理文本
    clean_text = preprocess_text(text)

    # 获取停用词
    stopwords = get_default_stopwords()

    # 分词
    words = tokenize_text(clean_text, stopwords)

    # 统计词频
    top_words = count_words(words, top_n=50)

    # 打印热词统计结果
    print("\n两会政府工作报告热词统计:")
    for word, count in top_words:
        print(f"{word}: {count} 次")

    # 询问是否使用掩码图像
    use_mask = input("是否使用掩码图像?(y/n, 默认 n):").lower().startswith('y')
    mask_image = None
    if use_mask:
        mask_image = input("请输入掩码图像路径(例如 'china_map.png'):")

    # 询问是否保存词云图
    save_image = input("是否保存词云图?(y/n, 默认 n):").lower().startswith('y')
    output_file = None
    if save_image:
        output_file = input("请输入保存文件名(例如 'wordcloud.png'):")

    # 生成词云图
    generate_wordcloud(top_words, mask_image, output_file)


if __name__ == "__main__":
    main()

​

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值