pyhton词云
首先安装相关依赖
pip install wordcloud
简单的示例代码
# 导入词云制作第三方库wordcloud
import wordcloud
# 创建词云对象,赋值给w,现在w就表示了一个词云对象
w = wordcloud.WordCloud()
# 调用词云对象的generate方法,将文本传入
w.generate('and that government of the people, by the people, for the people, shall not perish from the earth.')
# 将生成的词云保存为output1.png图片文件,保存出到当前文件夹中
w.to_file('output1.png')
通过上述四行代码就可以简单生成词云,wordcloud库会非常智能地按空格进行分词及词频统计,出现次数多的词就大。
爬取重要讲话并制作词云
这里使用scrapy框架进行文章爬取。
import scrapy
import wordcloud
class SpeechspiderSpider(scrapy.Spider):
name = 'speechspider'
# allowed_domains = ['www.xxx.com']
start_urls = ['https://www.sohu.com/a/450418486_114731']
def parse(self, response):
content=response.xpath("//article[@class='article']/p/text()").extract()
content.pop(0)
content.pop()
content="".join(content)
w=wordcloud.WordCloud(width=1000,height=800,background_color='white',font_path="msyh.ttc")
w.generate(content)
w.to_file("./speech.png")
爬取成功,词云生成