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

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

在这里插入图片描述

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值