用python给我编写一个程序,这个程序是这样的:从网上获取任意英文文本素材,分词后统计词频,将高频词用第三方库wordcloud可视化为词云。
时间: 2023-06-09 19:02:26 浏览: 63
好的,我可以为您编写这个程序。首先,我们需要安装一些Python库,包括requests、nltk和wordcloud。在命令行中输入以下命令以安装这些库:
pip install requests nltk wordcloud
安装完成后,您可以按照以下步骤编写程序:
1.导入必要的库
import requests
from bs4 import BeautifulSoup
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from wordcloud import WordCloud
import matplotlib.pyplot as plt
2.获取任意英文文本素材并分词
url = 'https://www.gutenberg.org/files/1342/1342-0.txt'
response = requests.get(url)
text = response.text
# 去除标点符号和数字
text = ''.join([i for i in text if i.isalpha() or i.isspace()])
tokens = word_tokenize(text)
3.统计词频
# 去除停用词
stop_words = set(stopwords.words('english'))
filtered_tokens = [token for token in tokens if not token in stop_words]
# 计算词频
freq_dict = {}
for token in filtered_tokens:
if token in freq_dict:
freq_dict[token] += 1
else:
freq_dict[token] = 1
4.绘制词云
wordcloud = WordCloud(width=800, height=800, background_color='white')
wordcloud.generate_from_frequencies(frequencies=freq_dict)
plt.figure(figsize=(8,8))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()
这个程序可以获取Gutenberg项目的《傲慢与偏见》一书,您可以将URL替换为任何英文文本素材的URL。之后,程序会将文本分词并统计词频,最后绘制一个词云。
希望这个程序能够满足您的需求,如果您有任何问题,请随时联系我。