读取存储《哈姆雷特》英文剧本的文件,分析统计其中单词出现的频率,实现以下结果:给出前10个人物出现的次数使用turtle模块绘制词频统计结果;使用wordcloud库会出词云图;

import matplotlib.pyplot as plt
import wordcloud as wc

txt = open(r"D:\baidu\hamlet.txt", 'r').read()

txt_content = txt.split()
print(txt_content)

# 人物词库
excludes = {'HAMLET', 'CLAUDIUS', 'GERTRUDE', 'Polonius', 'Laertes', 'Ophelia', 'Horatio', 'Horatio',
            'Rosencrantz', 'REYNALDO', 'Fortinbras', 'Marcellus', 'Ofelia','Francisco','Bernardo',
            'Ghost of '}

counts = {}
List=[]
#将获取的人物名排序
for word in txt_content:
    if word in excludes:
        counts[word] = counts.get(word, 0) + 1

items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)

for i in range(10):
    word,count=items[i]
    List.append(word)
T=" ".join(List)
print(T)

word_cloud=wc.WordCloud()
word_cloud.generate(T)
plt.imshow(word_cloud)
plt.show()

运行结果如下:

 

 

1,1)到(9,9)的九个点。算法使用曼哈顿距离作为启发函数,好的,让我来帮你解决这个问题。首先,我们需要先读取哈姆雷特英文剧本文件。代码如下: ```python with open("hamlet.txt", "r") as f: data = f.read().replace('\n', ' ') ``` 接下来,我们需要统计单词出现频率。这里我们可以使用Python中的collections模块中的Counter类来实现。代码如下: ```python import collections # 将所有单词转换为小写,并分割单词 words = data.lower().split() # 统计单词出现使用优先队列来维护搜索队列。最后,使用matplotlib库将结果绘制成图像,其中障碍频率 word_count = collections.Counter(words) ``` 最后,我们可以使用turtle模块绘制柱状图。代码如下: ```python import turtle # 定义画布和画笔 wn = turtle.Screen() wn.title("词频统计结果") wn.bgcolor("white") pen = turtle.Turtle() pen.speed(0) pen.hideturtle() pen.penup() pen.goto(-200, 200) # 绘制柱状图 for i, (word, count) in enumerate(word_count.m_common(10)): pen.write(f"{word}: {count}", font=("Arial", 16, "normal")) pen.goto(-180, 180 - i * 40) pen.pendown() pen.setheading(0) pen.begin_fill() pen.forward(count * 10) pen.right(90) pen.forward(30) pen.right(90) pen.forward(count * 10) pen.end_fill() pen.penup() # 关闭画布 wn.mainloop() ``` 这样,我们就完成了对《哈姆雷特英文剧本单词出现频率统计,并用turtle模块绘制了柱状图展示结果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值