1. 程式人生 > >python讀寫txt檔案,並用jieba庫進行中文分詞

python讀寫txt檔案,並用jieba庫進行中文分詞

在虎撲上隨便找了一段文字,貼上到word.txt檔案中,然後對這段文字進行處理。其中用到的matplotlib庫,主要是用來繪圖;jieba庫,對文字進行分詞;wordcloud庫,構建詞雲。一、引用庫
import jieba
import matplotlib as mpl
import matplotlib.pyplot as plt
from wordcloud import WordCloud
二、讀取txt檔案
#定義一個空字串
final = ""
#資料夾位置
filename = r"E:\Program Files\爬蟲\word.txt"

#開啟資料夾,讀取內容,並進行分詞
with open(filename,'r',encoding = 'gb2312') as f:
    for line in f.readlines():
        word = jieba.cut(line)
        for i in word:
            final = final + i +" "
三、構造詞雲
word_pic = WordCloud(font_path = r'C:\Windows\Fonts\simkai.ttf',width = 2000,height = 1000).generate(final)
plt.imshow(word_pic)
#去掉座標軸
plt.axis('off')
#儲存圖片到相應資料夾
plt.savefig(r'E:\Program Files\6.png')
最後生成的圖片如下: