Python单词出现的频率怎样计算
时间: 2023-06-20 17:03:36 浏览: 45
Python单词的出现频率可以通过以下步骤计算:
1. 将文本文件读入Python中
2. 将所有的大写字母转换成小写字母,以避免单词大小写不匹配
3. 去除所有的标点符号和特殊字符,只留下单词
4. 将所有的单词转换成字典中的键,并将出现次数记录在字典的值中
5. 对字典按照值进行排序,输出出现频率最高的单词
示例代码:
```python
import string
def count_words(filename):
"""计算单词出现的频率"""
# 创建空字典
word_counts = {}
# 打开文件
with open(filename) as file:
# 遍历文件中的每一行
for line in file:
# 去除空格和换行符
line = line.strip()
# 去除标点符号和特殊字符
line = line.translate(str.maketrans("", "", string.punctuation)) # string.punctuation包含所有的标点符号
# 将大写字母转换成小写字母
line = line.lower()
# 拆分行中的单词
words = line.split()
# 遍历所有的单词,并将出现次数记录在字典中
for word in words:
if word not in word_counts:
word_counts[word] = 1
else:
word_counts[word] += 1
# 对字典按照值进行排序
sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
# 输出出现频率最高的单词
for word, count in sorted_word_counts[:10]:
print(word, count)
# 测试
count_words("test.txt")
```
上述代码中打开的文件名为 test.txt,可以根据需要进行修改。输出结果中包含出现频率最高的前10个单词及其出现次数。