4.从网上自行下载一个长篇英文小说(除课堂讲授的哈姆雷特外),统计并输出该小说中词频最大的TOP 20结果。利用该文本和wordcloud库、imageio库等,生成一个属于自己的词云图形。
时间: 2024-02-05 10:10:44 浏览: 30
好的,我可以帮你完成这个任务。以下是操作步骤:
1. 首先,你需要在网上下载一本长篇英文小说,并将其保存在本地。在此我以《The Great Gatsby》为例,将其保存在本地并命名为`gatsby.txt`。
2. 接着,你需要使用Python读取该文本文件并进行词频统计。以下是代码实现:
```python
import re
from collections import Counter
# 读取文本文件
with open('gatsby.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用正则表达式去除标点符号和数字
text = re.sub(r'[^\w\s]', '', text)
text = re.sub(r'\d+', '', text)
# 将文本转为小写
text = text.lower()
# 统计词频
words = text.split()
word_count = Counter(words)
# 输出词频最大的TOP 20结果
top_20 = word_count.most_common(20)
for word, count in top_20:
print(word, count)
```
运行以上代码后,即可在控制台输出词频最大的TOP 20结果。
3. 接下来,你需要安装并导入`wordcloud`库和`imageio`库。如果你还没有安装这两个库,可以使用以下命令进行安装:
```
pip install wordcloud imageio
```
导入库的代码如下:
```python
import wordcloud
import imageio
```
4. 最后,你可以使用以下代码生成词云图形:
```python
# 生成词云图形
mask = imageio.imread('mask.png')
wc = wordcloud.WordCloud(background_color='white', mask=mask)
wc.generate_from_frequencies(word_count)
wc.to_file('wordcloud.png')
```
以上代码中,`mask.png`是用于生成词云形状的图片文件,你可以使用任意形状的图片,将其保存在本地并替换代码中的文件名。`background_color`参数用于设置词云背景颜色,默认为黑色,这里我将其设置为白色。`generate_from_frequencies`方法用于根据词频生成词云,`to_file`方法用于将词云保存为图片文件。运行以上代码后,即可在当前目录下生成名为`wordcloud.png`的词云图形。
希望以上操作步骤能够帮助到你。