Python词频统计与词云制作

在之前的文章中,我们已经掌握了如何利用 requests 库进行京东商品评论的采集。今天,我们将继续深入处理这些采集到的数据,进行词频统计并制作词云图片。让我们一步步来完成这个过程。

一、安装依赖

首先,我们需要安装 jieba 和 wordcloud 这两个库,它们将帮助我们实现中文分词和词云生成的功能。

二、分词

利用jieba库对文本进行分词,jieba.lcut 直接生成的就是一个list,jieba支持三种分词模式:

  • 精确模式lcut(),试图将句子最精确地切开,适合文本分析,单词无冗余;
  • 全模式lcut(s, cut_all=True) ,把句子中所有的可以成词的词语都扫描出来,速度非常快,但是不能解决歧义,存在冗余;
  • 搜索引擎模式cut_for_search(s),在精确模式的基础上,对长词再次切分,提高召回率,适合用于搜索引擎分词。
 file = open(file_path, 'r')
    txt = file.read()
    words = jieba.lcut(txt)

三、词频统计

对分词结果进行词频统计,这里我们将针对京东商品评论中的手机特点进行分析。为了获得准确的统计结果,我们还需要剔除一些与手机特点无关的词汇。这可以通过引入停用词列表并遍历删除实现,最终得到精确的词频统计结果,按频率由高到低排序。

count = {}
    for word in words:
        if len(word) == 1:
            continue
        else:
            count[word] = count.get(word, 0) + 1
    # 引入停用词
    exclude = ["手机", "其他", "非常", "使用", "一天"]  # 建立无关词语列表
    for key in list(count.keys()):  # 遍历字典的所有键,即所有word
        if key in exclude:
            del count[key]
    lists = list(count.items())
    lists.sort(key=lambda x: x[1], reverse=True) 

四、保存词频统计结果

将统计好的词频结果写入文件中。

 with open(word_path, 'w', encoding='gbk') as f:
        for i in range(15):
            word, number = lists[i]
            f.write('{}\t{}\n'.format(word, number))
        f.close()
        return word_path 

五、生成词云

使用 wordcloud 库生成词云图片。通过 generate(text) 函数,我们可以根据给定的文本生成词云。你可以自定义词云的字体、图片大小、背景颜色以及形状

def get_cloud(word_path):
    with open(word_path, 'r', encoding='gbk') as f:
        text = f.read()
    wcloud = wordcloud.WordCloud(font_path=r'C:\Windows\Fonts\simhei.ttf',
                                 background_color='white',
                                 width=1000,
                                 max_words=1000,
                                 height=860,
                                 margin=2).generate(text)
    wcloud.to_file('E:/python/resource/' + 'cloud.png')  # 指定词云文件路径
    f.close()
    print("词云图片已保存") 

效果如下:
在这里插入图片描述

总结

通过以上步骤,我们成功地对采集到的京东商品评论进行了词频统计并制作了词云图片。这个过程涵盖了分词、词频统计、结果剔除等环节,最终呈现出了一个清晰、美观的词云图。这个方法可以用于分析用户对商品的评价和关注点,有助于提取出商品的优点和特点,为市场营销和产品改进提供有价值的信息。

附源代码:

import jieba
import wordcloud

# 对文本进行分词
def cut_word(file_path):
    file = open(file_path, 'r')
    txt = file.read()
    words = jieba.lcut(txt)
    # 对词频进行统计
    count = {}
    for word in words:
        if len(word) == 1:
            continue
        else:
            count[word] = count.get(word, 0) + 1
    # 引入停用词
    exclude = ["手机", "其他", "非常", "使用", "一天"]  # 建立无关词语列表
    for key in list(count.keys()):  # 遍历字典的所有键,即所有word
        if key in exclude:
            del count[key]
    lists = list(count.items())
    lists.sort(key=lambda x: x[1], reverse=True)#词频排序
    # 打印前15条词频
    for i in range(20):
        word, number = lists[i]
        print("关键字:{:-<5}频次:{}".format(word, number))
    # 词频写入
    with open(word_path, 'w', encoding='gbk') as f:
        for i in range(20):
            word, number = lists[i]
            f.write('{}\t{}\n'.format(word, number))
        f.close()
        return word_path

# 制作词云
def get_cloud(word_path):
    with open(word_path, 'r', encoding='gbk') as f:
        text = f.read()
    wcloud = wordcloud.WordCloud(font_path=r'C:\Windows\Fonts\simhei.ttf',
                                 background_color='white',
                                 width=500,
                                 max_words=1000,
                                 height=400,
                                 margin=2).generate(text)
    wcloud.to_file('E:/python/resource/' + 'cloud1.png')  # 指定词云文件路径
    f.close()
    print("词云图片已保存")

file_path = 'E:/python/resource/comments.txt'
word_path = 'E:/python/resource/wordcloud.txt'

if __name__ == '__main__':
    cut_word(file_path)
    get_cloud(word_path) 

如有错误,欢迎私信纠正,谢谢支持!

posted @ 2022-11-16 18:06  杨业壮  阅读(724)  评论(0编辑  收藏  举报