安装jieba库
老师给的秘密花园是中文文档,上网搜索python中文文档词频统计,照着这篇博文来操作:使用python进行“中文词频分析”学习笔记
jieba库的作用:给中文文档分词。
博文说直接打开cmd,然后pip install jieba即可。但我试了下,失败了,出来很多红字…
于是一顿乱搜,发现有人也是这样,改用国内镜像就行了。我试了下,诶嘿…真的可以。
命令如下:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple jieba
一个经验教训:
- jieba库要装在保存py文件的目录下
(就是装python作业的那个文件夹。)
涉及到的命令:- e:
- cd xxxx (就一直cd 回车 直到那个目录)
- (哎 应该也没人 没事不丢人 记给自己看。。我真的好菜 )
虽说提示要更新,upgrade什么的,但我没更新好像也行。
敲代码
对着博文敲,自己找了个停用词表,复制到txt里。一开始存到桌面,结果运行报错。要存到同一个目录下。后面就可以了。哈哈哈哈哈哈哈开心(为何菜的如此心安理得)
import jieba
txt = open("secret.txt", encoding = "utf-8").read()
#加载停用词表
stopwords = [line.strip() for line in open("stop.txt",encoding="utf-8").readlines()]
words = jieba.lcut(txt)
counts = {}
for word in words:
if word not in stopwords:
if len(word) == 1:
continue
else:
counts[word] = counts.get(word,0) + 1
items = list(counts.items())
items.sort(key = lambda x:x[1], reverse = True)
print("词 词频\n——————————")
for i in range(50):
word, count = items[i]
#print(i+1)
print ("{:<10}{:>7}".format(word,count))
if i+1 ==10:
print("\n———前10名————\n")
elif i+1 == 30:
print("\n———10-30名————\n")
elif i+1 == 50:
print("\n———30-50名————\n")