使用python爬取豆瓣评论,生成词云图

Python爬取豆瓣评论生成词云图教程
本文介绍了如何使用Python的requests和parsel库爬取豆瓣评论,结合jieba进行分词,再利用wordcloud库生成词云图。详细步骤包括获取评论内容、数据解析、写入文本及展示词云效果。

开发工具

pycharm

第三方放库

requests模块

pip install reqeusts  网络请求库

parsel模块

pip install parsel  数据解析库

 词云模块

pip install wordcloud 词云库

pip install jieba 分词库

 代码分析

1、获取评论页的内容

url = 'https://movie.douban.com/subject/34841067/comments?status=P'
header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'}
rest = requests.get(url=url, headers=header)   #  携带请求头

2、数据解析

result = parsel.Selector(rest.text) 将html网页数据进行解析
result_s = result.xpath("//span [@class = 'short']/text()") 使用xpath进行数据匹配

3、将内容写入文本

f = open('你好,李焕英.txt', 'a', encoding='utf-8')  # 打开文件
for item in result_s:
    f
以下是一个使用Python爬取豆瓣最新评论生成词云图的示例代码: ```python import requests from bs4 import BeautifulSoup import jieba from wordcloud import WordCloud import matplotlib.pyplot as plt # 爬取豆瓣评论的函数 def get_comments(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') comments = soup.find_all('span', class_='short') return [comment.get_text() for comment in comments] # 生成的函数 def generate_wordcloud(text): wordcloud = WordCloud(font_path='simhei.ttf', background_color='white', width=800, height=600).generate(text) plt.imshow(wordcloud, interpolation='bilinear') plt.axis('off') plt.show() # 主函数 def main(): url = 'https://movie.douban.com/subject/1292052/comments?status=P' # 替换为你要爬取豆瓣电影页面URL comments = get_comments(url) text = ' '.join(comments) text = ' '.join(jieba.cut(text)) generate_wordcloud(text) if __name__ == '__main__': main() ``` 这段代码的主要功能如下: 1. 使用requests库爬取豆瓣评论页面。 2. 使用BeautifulSoup解析HTML内容,提取评论文本。 3. 使用jieba库对文本进行分。 4. 使用wordcloud库生成词云图。 5. 使用matplotlib库显示生成词云图使用这段代码时,请注意以下几点: 1. 确保安装了所需的Python库:requests, bs4, jieba, wordcloud, matplotlib。 2. 将font_path参数设置为本地中文字体文件路径,以确保中文能正确显示。 3. 修改url变量为你想要爬取豆瓣电影页面URL。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

python 扫地僧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值