直入主题,我们需要用到jieba库的一些函数,这个python库是国内大神编写的。
我们需要用到文件的一部分内容,这里我们还需要两个txt文本
1.水浒传部分文本(也可以是全部文本)
2.水浒传内所有完整的姓名(除称号外)
文本在网上可以找得到,我直接上代码了
import jieba
txt=open("AllManAreBrothers.txt","rb").read()
txt_name=open("heros_name.txt","rb").read()
words=jieba.lcut(txt)
words_name=jieba.lcut(txt_name)
counts={}
for word in words:
if len(word)==1:
continue
if word not in words_name:
continue
counts[word]=counts.get(word,0)+1
sorted(counts.items(), key=lambda x:x[0], reverse=True)
for i in range(10):
word,count=items[i]
print("{0:<10}{1:>5}".format(word,count))
- import jieba声明jieba库
- 这里第一个文本名是部分水壶的文本,第二个文本名是姓名的文本
- 用两个变量去承接两个jieba库的函数,这个 ji