import matplotlib.pyplot as plt import wordcloud as wc txt = open(r"D:\baidu\hamlet.txt", 'r').read() txt_content = txt.split() print(txt_content) # 人物词库 excludes = {'HAMLET', 'CLAUDIUS', 'GERTRUDE', 'Polonius', 'Laertes', 'Ophelia', 'Horatio', 'Horatio', 'Rosencrantz', 'REYNALDO', 'Fortinbras', 'Marcellus', 'Ofelia','Francisco','Bernardo', 'Ghost of '} counts = {} List=[] #将获取的人物名排序 for word in txt_content: if word in excludes: counts[word] = counts.get(word, 0) + 1 items = list(counts.items()) items.sort(key=lambda x: x[1], reverse=True) for i in range(10): word,count=items[i] List.append(word) T=" ".join(List) print(T) word_cloud=wc.WordCloud() word_cloud.generate(T) plt.imshow(word_cloud) plt.show()
运行结果如下: