如何python统计单词出现次数并输出排在前五的单词及出现的次数
时间: 2023-09-03 09:12:54 浏览: 62
可以使用Python中的字典来实现单词出现次数的统计,具体步骤如下:
1. 读取文本文件并将其转换为字符串。
2. 将字符串分割成单词列表。
3. 遍历单词列表,使用字典记录每个单词出现的次数。
4. 对字典按照单词出现次数进行排序,并输出前五个单词及其出现次数。
下面是代码示例:
```python
with open('text.txt', 'r') as f:
text = f.read().replace('\n', ' ').lower() # 读取文本文件并转换为小写字符串
words = text.split() # 将字符串分割成单词列表
word_count = {} # 创建空字典用于记录单词出现次数
for word in words:
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1 # 遍历单词列表,统计单词出现次数
sorted_word_count = sorted(word_count.items(), key=lambda x: x[1], reverse=True) # 按照单词出现次数进行排序
print("前五个单词及其出现次数:")
for i in range(5):
print(f"{sorted_word_count[i][0]}:{sorted_word_count[i][1]}") # 输出前五个单词及其出现次数
```
其中,`text.txt`是要统计的文本文件名,可以根据具体情况进行修改。