Python中爬虫后的Excel数据进行词频分析,并输出所有数据的词频的代码
时间: 2024-05-05 13:19:14 浏览: 20
以下是Python爬虫爬取数据并进行词频分析的代码示例:
```python
import requests
from bs4 import BeautifulSoup
import xlwt
import jieba
# 爬取数据
url = 'https://xxxxxx'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
content = soup.find('div', class_='content').text
# 分词
words_list = jieba.cut(content, cut_all=False)
words = ' '.join(words_list)
# 统计词频
word_counts = {}
for word in words.split():
if word not in word_counts:
word_counts[word] = 1
else:
word_counts[word] += 1
sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
# 写入Excel
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('词频统计')
row = 0
for item in sorted_word_counts:
worksheet.write(row, 0, item[0])
worksheet.write(row, 1, item[1])
row += 1
workbook.save('word_freq.xls')
```
请注意,在这个示例代码中,我们使用了jieba库进行了中文分词。由于不知道你的Excel数据的具体格式,因此我只写了将词频结果写入Excel表格的代码。在实际使用时,你需要对上述代码进行一些修改以适合你的具体场景。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)