網上看到一個txt文本信息,共2351條飯否記錄,據說是微信之父每天發的飯否記錄,其實我不知道什么是飯否。我讀取這個文本內容,展示到詞語圖上。之前也使用過,但是好久沒有玩Python了,稱假期空閑,練習練習。開始發行“通過網頁”變成了高頻詞匯,一看源文本文件,發行每條記錄的后面都包含“ 2010-11-26 13:59 通過網頁”,這樣通過網頁肯定是高頻詞了,所有重新處理了源文本信息,使用正則表達式式,提前時間節點前的任意字符。使用的正則表達式:.+(?=(\d{4}\-\d{2}\-\d{2}))
提前信息如下:
找一個背景,網上找奮斗圖片,去掉背景色,裁剪人物。
完整代碼:
from osimport path
from PILimport Image
import numpyas np
import matplotlib.pyplotas plt
import os
import chardet
from wordcloudimport WordCloud, STOPWORDS
# get data directory (using getcwd() is needed to support running example in generated IPython notebook)
d = path.dirname(__file__)if "__file__" in locals()else os.getcwd()
print(d)
# Read the whole text.
# text = open(path.join(d, 'ZXL.txt'), encoding='utf-8', errors='ignore').read()
with open(path.join(d, 'ZXL.txt'), 'rb')as f:
raw_data = f.read()
result = chardet.detect(raw_data)
use_encoding = result['encoding']
# 查看文本使用的編碼
print(use_encoding)# utf-8
text =open(path.join(d, 'ZXL.txt'), 'r', encoding=use_encoding).read()
# read the mask image
fight_mask = np.array(Image.open(path.join(d, "fight.png")))
# 指定字體文件路徑
font_path =r'C:\Windows\Fonts\方正粗黑宋簡體.ttf'
# 創建詞云圖對象并設置字體
stopwords =set(STOPWORDS)
wc = WordCloud(background_color="white",
? ? ? ? ? ? ? max_words=6000, mask=fight_mask,
? ? ? ? ? ? ? font_path=font_path,
? ? ? ? ? ? ? stopwords=stopwords,
? ? ? ? ? ? ? contour_width=3,
? ? ? ? ? ? ? contour_color='steelblue')
# generate word cloud
wc.generate(text)
# store to file
wc.to_file(path.join(d, "ZXL_example.png"))
# show
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.show()
運行效果如下:
生產圖片文件: