编写Python程序,爬 取 网 页http://www.gov.cn/xinwen/2021-06/13/content 5617433.htm新 闻 内 容 ,并 进 行 分 词 和 词 频 统 计 将 高 频 词 生 成 词 云 显 示。 建议:模块化编程,分为几个函数实现。
时间: 2024-01-18 21:02:21 浏览: 19
好的,我可以帮您解决这个问题。首先需要安装一些 Python 库,包括 requests、BeautifulSoup4、jieba、wordcloud 等。您可以通过以下命令进行安装:
```
pip install requests
pip install BeautifulSoup4
pip install jieba
pip install wordcloud
```
然后,可以编写一个 Python 程序,实现爬取网页、分词、词频统计和生成词云的功能。以下是一个示例程序:
```python
import requests
from bs4 import BeautifulSoup
import jieba
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt
def get_html(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)
html = response.content.decode('utf-8')
return html
def get_text(html):
soup = BeautifulSoup(html, 'html.parser')
text = soup.find('div', class_='content').get_text()
return text
def cut_words(text):
words = [word for word in jieba.cut(text) if len(word) >= 2]
return words
def count_words(words):
word_counts = Counter(words)
return word_counts
def generate_wordcloud(word_counts):
wc = WordCloud(font_path='simhei.ttf', max_words=100, width=1920, height=1080)
wc.generate_from_frequencies(word_counts)
plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.show()
if __name__ == '__main__':
url = 'http://www.gov.cn/xinwen/2021-06/13/content_5617433.htm'
html = get_html(url)
text = get_text(html)
words = cut_words(text)
word_counts = count_words(words)
generate_wordcloud(word_counts)
```
这个程序中,`get_html()` 函数用于获取网页的 HTML 内容,`get_text()` 函数用于从 HTML 中提取新闻内容,`cut_words()` 函数用于对新闻内容进行分词,`count_words()` 函数用于统计词频,`generate_wordcloud()` 函数用于生成并显示词云。
注意,为了能够显示中文字符,需要在 `generate_wordcloud()` 函数中指定字体文件路径,例如这里使用了 `simhei.ttf` 字体。如果您的电脑中没有该字体文件,可以在网上下载并放置到程序所在目录下。
另外,为了能够在 Jupyter Notebook 中显示词云,需要使用以下代码替换 `plt.show()`:
```python
from IPython.display import display, HTML
display(HTML('<img src="%s">' % wc.to_image().to_data_uri())))
```
这样就可以在 Jupyter Notebook 中显示词云了。