linyx
时间: 2023-08-04 16:07:11 浏览: 35
好的,那么我们可以使用Python来进行这个任务。首先,我们需要下载《哈姆雷特》的英文剧本。你可以从网上搜索并下载该文件,保存为一个文本文件。假设你已经将文件保存为了名为"hamlet.txt"的文本文件。
接下来,我们需要编写Python代码来对该剧本文件进行处理,统计单词出现的频率,并使用turtle模块绘制柱状图。下面是一个示例代码,你可以参考并根据自己的需求进行修改:
```python
import turtle
from collections import Counter
# 读取文件内容
with open('hamlet.txt', 'r') as f:
text = f.read()
# 将文本转换为小写,并去除标点符号和换行符
text = text.lower()
text = text.replace('\n', ' ')
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~':
text = text.replace(ch, '')
# 统计单词出现的频率
words = text.split()
word_counts = Counter(words)
word_freqs = []
for word, count in word_counts.items():
word_freqs.append((word, count))
# 对单词按照出现频率从高到低排序
word_freqs.sort(key=lambda x: x[1], reverse=True)
# 取出前20个出现频率最高的单词及其出现次数
top_words = word_freqs[:20]
labels = [x[0] for x in top_words]
counts = [x[1] for x in top_words]
# 使用turtle模块绘制柱状图
turtle.setup(800, 600)
turtle.title('Word Frequency')
turtle.setworldcoordinates(-1, -1, len(labels), max(counts) + 1)
turtle.hideturtle()
turtle.speed('fastest')
for i in range(len(labels)):
turtle.penup()
turtle.goto(i, 0)
turtle.pendown()
turtle.begin_fill()
turtle.fillcolor('gray')
turtle.setheading(90)
turtle.forward(counts[i])
turtle.right(90)
turtle.forward(0.8)
turtle.right(90)
turtle.forward(counts[i])
turtle.end_fill()
turtle.penup()
turtle.goto(i, 0)
turtle.pendown()
turtle.setheading(90)
turtle.forward(counts[i] + 0.5)
turtle.write(labels[i], align='center', font=('Arial', 10, 'normal'))
turtle.done()
```
这段代码会读取"hamlet.txt"文件,将文本转换为小写并去除标点符号和换行符,然后统计单词出现的频率,并对单词按照出现频率从高到低排序。接着,取出前20个出现频率最高的单词及其出现次数,并使用turtle模块绘制柱状图。最后,展示绘制的柱状图。
你可以根据自己的需要修改这段代码,并将其保存为一个Python文件,然后在终端中运行该文件来执行该任务。