使用Python生成词云,分析政府工作报告热词

引言: 

       在这篇博客中,我将分享如何使用Python进行文本数据的分析与可视化,具体来说,将从“政府工作报告”提取的文本中分析热词,并且生成词云图像。这不仅可以帮助我们直观了解报告中的高频关键词,还为文本分析提供了一个良好的例子。

实现思路:

文本数据分析的基本步骤包括以下几点:

  1. 读取文本:首先需要读取文本数据。可以从一个存储纯文本的文件中读取你需要分析的文本。
  2. 数据预处理:这一步包括去除非汉字字符,确保我们处理的主要是中文内容。
  3. 分词:使用中文分词工具对文本进行分词,这里选择了jieba库。
  4. 去除停用词:一些无意义的词(比如“的”、“是”等)对分析有干扰,需要去掉。通常需要一个停用词表。
  5. 统计词频:采用collections.Counter来统计每个词出现的频率。
  6. 生成词云:利用WordCloud库,将词频结果转化为直观的词云图。

 代码实现:

import jieba
from collections import Counter
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import re

# 从政府工作报告中提取了纯文本并存储在一个文件中
file_path = '工作报告.txt'

def read_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        text = file.read()
    return text

def preprocess_text(text):
    # 去除非汉字字符
    text = re.sub(r'[^\u4e00-\u9fff]', '', text)
    return text

def segment_text(text):
    # 使用jieba进行分词
    words = jieba.lcut(text)
    return words

def filter_stopwords(words, stopwords_path='stopwords.txt'):
    with open(stopwords_path, 'r', encoding='utf-8') as file:
        stopwords = {line.strip() for line in file}
    
    filtered_words = [word for word in words if word not in stopwords and len(word) > 1]
    return filtered_words

def print_top_words(word_freq, top_n=10):
    top_words = word_freq.most_common(top_n)
    print("Top {} words: ".format(top_n))
    for word, freq in top_words:
        print(f"{word}: {freq}")

def generate_word_cloud(word_freq):
    wordcloud = WordCloud(
        font_path='simhei.ttf',
        width=1600,
        height=1200,
        background_color='white'
    ).generate_from_frequencies(word_freq)
    
    plt.figure(figsize=(12, 8), dpi=200)
    plt.imshow(wordcloud, interpolation='bilinear')
    plt.axis('off')
    plt.show()

def main():
    text = read_file(file_path)
    text = preprocess_text(text)
    words = segment_text(text)
    filtered_words = filter_stopwords(words)
    word_freq = Counter(filtered_words)

    # 打印词频
    print_top_words(word_freq, top_n=10)

    # 生成词云
    generate_word_cloud(word_freq)

if __name__ == '__main__':
    main()

代码运行结果

统计出的热词及频率:

 使用Python生成词云,分析政府工作报告热词_第1张图片

绘制出的云图: 

使用Python生成词云,分析政府工作报告热词_第2张图片

总结

       在本文中,我们通过分析政府工作报告的文本来理解重要的概念。词云为我们提供了一种视觉表达方式,以便快速识别报告中的主要内容。通过这样的文本分析,可以为进一步的研究以及专项分析提供基础。

你可能感兴趣的:(python,开发语言,软件工程)