#coding=utf8 # Python3.0+以后,可写可不写。 from wordcloud import WordCloud, ImageColorGenerator # 引入词云WordCloud import jieba # 引入分词的词典 import matplotlib.pyplot as plt # 制图包, as作用是重命名长度大的程序,方便引用写码 text = open('test2.txt','r',encoding='utf-8').read() ls = [] words = jieba.lcut(text) counts = {} for word in words: ls.append(word) 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(20): word, count = items[i] print("{:<10}{:>5}".format(word, count)) cut_text = ' '.join(jieba.cut(text)) # 让jieba把文本进行分词,从而词云显示“词组”而不是“句子“”。并重新命名为cut_text,以示区别。 wordcloud = WordCloud( background_color='white', # 默认为图片背景为黑色,英文White表示输出的词云图片背景为白色。 scale=15, # 默认之为1。可以理解为生成的图片像素密度值,值越大,图片密度越高,越清楚。 font_path='c:\windows\Fonts\simhei.ttf', # 写明地址,指定文字的类型为中文黑体。 ).generate(cut_text) # 运行成功后显示图片 plt.imshow(wordcloud, interpolation='bilinear') # Bilinear:双线性插值算法,用来缩放显示图片。缩放就是把原图片的像素应用坐标系统,用坐标表示,双线性插值算法就是把一个坐标不是整数的点的坐标,用最近的四个整数点坐标指示出来; plt.axis('off') # 不显示坐标尺度 plt.show()
爬虫生成中文词云代码
最新推荐文章于 2023-07-28 14:30:02 发布