jieba库

---恢复内容开始---

简介

◆ jieba库是优秀的中文分词第三方库

◆ jieba库和其他的第三方库一样,在cmd中使用pip install jieba 就可以进行安装

◆ jieba最常用的函数只有一个,

jieba库的三种模式及其函数

◆ 精确模式:jieba.lcut(s)    对文本s进行分词

◆ 全局模式:jieba.lcut(s,cut_all=True)   进行分词之后存在冗余

◆ 搜索引擎模式:jieba.lcut_for_search(s)   同样进行分词之后存在冗余

◆ jieba.add_words(w)    向分词词典中增加一个单词当然,

最常用的还是jieba.lcut(s),这个函数就基本上满足平时的需求了

jieba词频统计实例

代码

import jieba
txt=open("老九门.txt","r",encoding='utf-8').read()
words=jieba.lcut(txt)
new={}
for word in words:
    if len(word) == 1:
        continue
    elif word=="张大佛爷" or word=="佛爷":
        rword="张启山"
    else:
        rword=word
    new[rword]=new.get(rword,0)+1
exc={"事情","什么","已经","还是","说道"}
for word in exc:
    del new[word]
items=list(new.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))

 

运行结果

 1 #张启山          50
 2 #自己           28
 3 #没有           21
 4 #知道           20
 5 #一个           11
 6 #他们           11
 7 #不会           10
 8 #一样           10
 9 #不是           10
10 #东西           10
11 #看到            9
12 #张大            9
13 #看着            9
14 #解九            9
15 #长沙            8

 词云代码

 1 from wordcloud import WordCloud
 2 import matplotlib.pyplot as plt
 3 import jieba  # 生成词云def create_word_cloud(filename):
 4     text = open("{老九门}.txt".format(filename)).read()
 5     wordlist = jieba.cut(text, cut_all=True) # 结巴分词
 6     wl = " ".join(wordlist)     # 设置词云
 7     wc = WordCloud(        # 设置背景颜色
 8         background_color="black",        # 设置最大显示的词云数
 9         max_words=2000,        # 这种字体都在电脑字体中,一般路径        f
10         ont_path='simsun.ttf',
11         height=1200,
12         width=1600,        # 设置字体最大值
13         max_font_size=100,# 设置有多少种随机生成状态,即有多少种配色方案
14         random_state=100,
15     )
16     myword = wc.generate(wl)  # 生成词云    # 展示词云图
17     plt.imshow(myword)
18     plt.axis("off")
19     plt.show()
20     wc.to_file('img_book.png')  # 把词云保存下
21     if __name__ == '__main__':
22         create_word_cloud('mytext')

 多谢观赏!

posted @ 2019-04-03 13:23  .SG  阅读(406)  评论(0编辑  收藏  举报