爬虫生成中文词云代码

#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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值