您的位置:首页 > 编程语言 > Python开发

使用python对txt文本进行词频统计-学习笔记

2020-07-26 09:39 54 查看

1.下载安装jieba库

利用镜像下载安装

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple jieba

2. jieba库作用与功能概述

jieba库利用中文词库,对中文文本,通过分词,获得单个的词语

jieba库常用函数:

2.1 精确模式(把文本精确的切分开,不存在冗余单词)

2.1.1 jieba.cut(“菜篮子里面团着一条蛇”)
返回一个可迭代的数据类型

2.1.2 jieba.lcut(“菜篮子里面团着一条蛇”)
返回一个列表类型

2.2 全模式(把文本中所有可能的词语都扫描出来,有冗余词)

2.2.1 jieba.cut(“菜篮子里面团着一条蛇”, cut_all=True)
输出文本中所有可能的单词

2.2.2 jieba.lcut(“菜篮子里面团着一条蛇”, cut_all=True)
返回一个列表类型

2.3 搜索引擎模式(在精确模式基础上,对长词再次切分,适合搜索引擎建立索引的结果)

2.3.1 jieba.cut_for_search(“菜篮子里面团着一条蛇”)

2.3.2 jieba.lcut_for_search(“菜篮子里面团着一条蛇”)

3. 对txt文本进行词频统计(去除停用词)(词频显示)

import jieba

txt = open("斗罗大陆.txt", "r", encoding='utf-8').read()# 2.全职法师   加载txt文本
words = jieba.cut(txt)# 返回可迭代的数据
stop = open("stopwords.txt", "r", encoding='utf-8').read()# 加载停用词表

counts = {}# 创建列表

for word in words:
if word not in stop:# 去除停用词
if len(word) == 1:
continue# 如果字长为1则去除
else:
counts[word] = counts.get(word, 0) + 1# 字长不为1且不是停用词的词,频率加1
items = list(counts.items())# 转换为列表

items.sort(key=lambda x: x[1], reverse=True)# 对词频进行降序排序
for i in range(15):#输出频率最高的前十五个词
word, count = items[i]
print("{0:<10}{1:<5}".format(word, count))# 输出

4. 对txt文本进行词频统计(词云显示)

import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt

txt = open("斗罗大陆.txt", encoding='utf-8').read()# 加载txt文本
wordslist = jieba.cut(txt)# 返回可迭代的数据
wl = " ".join(wordslist)# 将序列中的元素以空格连接生成一个新的字符串

wc = WordCloud(font_path='C:/Users/Windows/fonts/STXINGKA.TTF',  # 设置字体
#background_color="white",  # 可以设置背景颜色为白色
max_words=150,  # 词云显示的最大词数
max_font_size=150,  # 字体最大值
random_state=60,# 设置有多少种配色方案
width=1200, height=700,# 设置图片的大小
).generate(txt)# 生成词云

plt.imshow(wc)# 对图像进行处理并显示格式
plt.axis("off")# 关闭坐标轴线和标签
plt.show()# 显示图像
wc.to_file('wordcloud.jpg')# 将词云输出为图片,保存为wordcloud.jpg/.png

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: