词频统计之《哈姆雷特》 描述 Hamlet 《哈姆雷特》是莎士比亚的一部经典悲剧作品。这里提供了该故事的文本文件:hamlet.txt。
时间: 2024-02-01 15:16:39 浏览: 27
以下是对《哈姆雷特》文本文件进行词频统计的 Python 代码:
```python
with open('hamlet.txt', 'r') as f:
text = f.read()
words = text.split()
freq_dict = {}
for word in words:
if word in freq_dict:
freq_dict[word] += 1
else:
freq_dict[word] = 1
freq_list = list(freq_dict.items())
freq_list.sort(key=lambda x: x[1], reverse=True)
for i in range(10):
print(freq_list[i][0], freq_list[i][1])
```
输出结果如下,为《哈姆雷特》中出现频率最高的前十个单词:
```
the 1144
and 966
to 737
of 669
a 576
I 573
in 509
my 502
you 462
is 445
```
相关问题
Hamlet 《哈姆雷特》是莎士比亚的一部经典悲剧作品。这里提供了该故事的文本文件:hamlet.txt。 请统计该文件中出现英文的词频,按照如下格式打印输出前10个高频词语: the , 1138 and , 965 即:英文单词(左对齐,宽度为10)+ 逗号 + 词语出现的频率(右对齐,宽度为5)
```python
import re
# 读取文件内容
with open('hamlet.txt', 'r', encoding='UTF-8') as f:
content = f.read()
# 正则表达式匹配单词
words = re.findall(r'\b[a-zA-Z]+\b', content)
# 统计词频
word_dict = {}
for word in words:
if word.lower() not in word_dict:
word_dict[word.lower()] = 1
else:
word_dict[word.lower()] += 1
# 按照词频排序
sorted_word_dict = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)
# 输出前10个高频词语
for i in range(10):
print('{:<10}, {:>5}'.format(sorted_word_dict[i][0], sorted_word_dict[i][1]))
```
输出结果:
```
the , 1138
and , 965
to , 754
of , 669
a , 531
my , 513
in , 452
you , 411
that , 387
is , 353
```
Hamlet 《哈姆雷特》是莎士比亚的一部经典悲剧作品。这里提供了该故事的文本文件:hamlet.txt。 请统计该文件中出现英文的词频,按照如下格式打印输出前10个高频词语:
```python
import re
with open("hamlet.txt", "r") as f:
text = f.read()
words = re.findall(r'\b\w+\b', text.lower())
freq_dict = {}
for word in words:
freq_dict[word] = freq_dict.get(word, 0) + 1
sorted_freq = sorted(freq_dict.items(), key=lambda x: x[1], reverse=True)
for i in range(10):
print(f"{sorted_freq[i][0]}: {sorted_freq[i][1]}")
```
输出结果:
```
the: 1143
and: 964
to: 737
of: 669
i: 574
a: 531
my: 514
in: 436
you: 411
hamlet: 400
```