Python统计一段英文中各单词出现的次数
时间: 2024-11-25 15:20:47 浏览: 38
python统计文章中单词出现次数实例
在Python中,你可以使用内置模块`collections`中的`Counter`来统计一段英文文本中每个单词出现的次数。以下是简单的步骤:
```python
from collections import Counter
import re
def word_frequency(text):
# 删除标点符号并将文本转为小写
text = re.sub(r'[^\w\s]', '', text).lower()
# 分割单词,并计算频率
words = text.split()
frequency = Counter(words)
return frequency
# 测试用法
text = "This is a sample sentence to count the frequency of each word."
word_counts = word_frequency(text)
for word, count in word_counts.items():
print(f"'{word}': {count}")
```
运行这段代码后,它会打印出文本中每个单词及其出现的次数。
阅读全文