、爬取baidunews.htm/静态网页里新闻标题文本,并进行词频统计,接照词频从高到低的顺序显示。 按照模块化思想: (1) getcontent(fileneame,path)获取html文本里的新闻标题返回 filename是文件名 path代表select (方法的筛选参数 《标签路径)返口新闻标题组成的字符串 (②词频统计:tongjicipin(txt) 统计新闻标题的词频 #txt 数据解析返回数据 (3)词云展示:show(txt)
时间: 2024-03-06 13:51:43 浏览: 138
好的,这个问题涉及到了三个模块,分别是获取新闻标题、词频统计和词云展示。我来逐个解释下:
1. 获取新闻标题
可以使用Python中的requests和BeautifulSoup库来获取html文本里的新闻标题。具体的步骤如下:
```python
import requests
from bs4 import BeautifulSoup
def getcontent(filename, path):
url = 'file://' + path + '/' + filename
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
title_list = soup.select(path)
title_str = ''
for title in title_list:
title_str += title.get_text()
return title_str
```
其中,filename和path分别是文件名和select方法的筛选参数(即标签路径),url构造一个文件路径,response获取网页内容,soup解析网页内容并筛选出新闻标题,最后将标题拼接成一个字符串并返回。
2. 词频统计
在获取到新闻标题的字符串后,需要进行词频统计。可以使用Python中的collections库来统计字符串中每个单词出现的次数,并按照词频从高到低的顺序显示。
```python
from collections import Counter
def tongjicipin(txt):
words = txt.split()
counter = Counter(words)
return counter.most_common()
```
其中,txt是获取到的新闻标题字符串,words将字符串分割成单词列表,counter统计每个单词出现的次数,most_common方法将统计结果按照词频从高到低排序并返回。
3. 词云展示
最后,需要将词频统计结果进行可视化展示,可以使用Python中的wordcloud库来生成词云图。具体的步骤如下:
```python
from wordcloud import WordCloud
import matplotlib.pyplot as plt
def show(txt):
counter = dict(tongjicipin(txt))
wordcloud = WordCloud(background_color="white")
wordcloud.generate_from_frequencies(counter)
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()
```
其中,txt是获取到的新闻标题字符串,tongjicipin方法用于统计词频,counter将统计结果转换成字典形式,wordcloud生成词云图,plt用于展示词云图。
以上就是三个模块的实现方法,可以将它们组合起来实现爬取新闻标题文本,并进行词频统计和词云展示的功能。
阅读全文
相关推荐
















