上一篇我们利用requests对京东商品的评论进行采集,今天我们对采集结果进行词频统计,并制作词云图片。
首先,准备好jieba
,wordcloud
这两个第三方库,并将其导入。
第一步,利用jieba库对文本进行分词,jieba.lcut 直接生成的就是一个list
jieba支持三种分词模式:
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
第四步,制作词云,generate(text) 由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("词云图片已保存")
最后,调用主函数执行程序,对文本进行词频统计并生成词云。
if __name__ == '__main__':
cut_word(file_path)
get_cloud(word_path)
附源代码:
# coding=gbk
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)
如有错误,欢迎私信纠正,谢谢支持!