Ready to work
- Associated libraries need to be ready, as detailed in import module required
- A novel text
- A white base map
Material List
"Novels
"White base map
Desired effect
Start of text === "
Import module
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
Configuration path
img_path = "mr.jpg"
font_path = r'C:\Windows\Fonts\simhei.ttf'
Prepared text
con = open('baixue.txt','r',encoding='utf8').read()
The main processing
mask = np.array(Image.open(img_path))
wc1 = WordCloud(font_path=font_path,background_color='white', mask=mask).generate(con)
fig = plt.figure(1)
plt.imshow(wc1)
plt.axis('off')
Display and save
# plt.show()
plt.savefig('wcmr.jpg',dpi=500)
The full code
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
# 图片路径
img_path = "timg.jfif"
# 字体路径
font_path = r'C:\Windows\Fonts\simhei.ttf'
# 小说路径
con = open('baixue.txt','r',encoding='utf8').read()
# 保存路径
save_path = 'wcmr.jpg'
### 打开作为轮廓的图片,并转为数组
mask = np.array(Image.open(img_path))
wc1 = WordCloud(font_path=font_path,background_color='white', mask=mask).generate(con)
fig = plt.figure(1)
plt.imshow(wc1)
plt.axis('off')
# plt.show()
plt.savefig(save_path,dpi=500)