jieba库对英文单词的统计
# -*- coding: utf-8 -*-
def get_text():
txt = open("1.txt", "r", encoding=‘UTF-8‘).read()
txt = txt.lower()
for ch in ‘!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~‘:
txt = txt.replace(ch, " ") # 将文本中特殊字符替换为空格
return txt
file_txt = get_text()
words = file_txt.split() # 对字符串进行分割,获得单词列表
counts = {}
for word in words:
if len(word) == 1:
continue
else:
counts[word] = counts.get(word, 0) + 1
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)
for i in range(5):
word, count = items[i]
print("{0:<5}->{1:>5}".format(word, count))
词云制作
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import jieba
def create_word_cloud(filename):
text = open("哈姆雷特.txt".format(filename)).read()
wordlist = jieba.cut(text, cut_all=True)
wl = " ".join(wordlist)
wc = WordCloud(
background_color="black",
max_words=2000,
font_path=‘simsun.ttf‘,
height=1200,
width=1600,
max_font_size=100,
random_state=100,
)
myword = wc.generate(wl)
plt.imshow(myword)
plt.axis("off")
plt.show()
wc.to_file(‘img_book.png‘)
if __name__ == ‘__main__‘:
create_word_cloud(‘mytext‘)
原文:https://www.cnblogs.com/gzzfh/p/12657928.html