中文詞頻統計與詞云生成

2022-05-16 20:55:58 字數 2618 閱讀 4598

中文詞頻統計

2. 從檔案讀取待分析文字。

3. 安裝並使用jieba進行中文分詞。

pip install jieba

import jieba

jieba.lcut(text)

4. 更新詞庫,加入所分析物件的專業詞彙。

jieba.add_word('天罡北斗陣')  #逐個新增

jieba.load_userdict(word_dict)  #詞庫文字檔案

轉換**:scel_to_text

5. 生成詞頻統計

6. 排序

7. 排除語法型詞彙,代詞、冠詞、連詞等停用詞。

stops

tokens=[token for token in wordsls if token not in stops]

8. 輸出詞頻最大top20,把結果存放到檔案裡

9. 生成詞云。

**如下:

1

import

jieba

2def

read_file():

3 f = open('

c:\\users\\leo\\desktop\\我當陰陽先生的那幾年.txt

', '

r', encoding='

utf-8')

4 content = f.read() #

通過檔案讀取字串 str

5f.close()

6return

content

7def

read_stops():

8 f = open('

c:\\users\\leo\\desktop\\stops_chinese.txt

', '

r', encoding='

utf-8')

9 content = f.read() #

通過檔案讀取字串 str

10f.close()

11return

content

12 text =read_file()

13 stops =read_stops().split()14#

新增不切割的詞

15 jieba.add_word('

三清書'

)16 jieba.add_word('

崔作非'

)17 jieba.add_word('

福澤堂')18

#分割19 words =jieba.lcut(text)20#

除掉stops

21 tokens = [token for token in words if token not

instops]

22 wcdict ={}

23"""

統計次數並排序

"""24

for word in

tokens:

25if len(word)==1:

26continue

27else

:28 wcdict[word] = wcdict.get(word,0)+1

29 wcls =list(wcdict.items())

30 wcls.sort(key=lambda x:x[1],reverse=true)

31for i in range(20):

32print

(wcls[i])

33 cut_text = "

".join(tokens)

34"""

生成詞云

"""35

from wordcloud import

wordcloud

36 ciyun =wordcloud().generate(cut_text)

37import

matplotlib.pyplot as plt

38plt.imshow(ciyun)

39 plt.axis("

off")40

plt.show()

41 ciyun.to_file(r'

')

詞頻統計截圖:

詞云展示:

主要問題:pycharm安裝第三方庫不成功,目測是pip的版本太低,大概就是版本問題,第三方的庫都安裝不了

解決方法:1.通過命令列安裝

中文詞頻統計與詞云生成

中文詞頻統計 追風箏的人 txt 2.從檔案讀取待分析文字。3.安裝並使用jieba進行中文分詞。pip install jieba import jieba jieba.lcut text 4.更新詞庫,加入所分析物件的專業詞彙。jieba.add word 天罡北斗陣 逐個新增 jieba.lo...

中文詞頻統計與詞云生成

中文詞頻統計 作業連線 2.從檔案讀取待分析文字。3.安裝並使用jieba進行中文分詞。pip install jieba import jieba jieba.lcut text 4.更新詞庫,加入所分析物件的專業詞彙。jieba.add word 天罡北斗陣 逐個新增 jieba.load us...

中文詞頻統計與詞云生成

2.從檔案讀取待分析文字。3.安裝並使用jieba進行中文分詞。pip install jieba import jieba jieba.lcut text 4.更新詞庫,加入所分析物件的專業詞彙。jieba.add word 天罡北斗陣 逐個新增 jieba.load userdict word ...