在python中任意给定一篇英语文章,统计其中单词出现的频率
时间: 2024-01-21 19:17:37 浏览: 95
可以使用Python中的字典来实现单词频率的统计。具体步骤如下:
1. 将文章中的单词全部转换成小写,以便能够正确统计单词出现的频率。
2. 使用Python的split()方法将文章按照空格进行分割,得到一个单词的列表。
3. 遍历单词列表,使用Python的字典来统计每个单词出现的频率。
4. 输出每个单词及其出现的次数。
下面是一个示例代码:
```python
article = "This is a sample article. It is used to demonstrate word frequency counting in Python."
# 将文章中的单词全部转换成小写
article = article.lower()
# 使用split()方法将文章按照空格进行分割,得到一个单词的列表
words = article.split()
# 使用Python的字典来统计每个单词出现的频率
freq = {}
for word in words:
if word in freq:
freq[word] += 1
else:
freq[word] = 1
# 输出每个单词及其出现的次数
for word, count in freq.items():
print(f"{word}: {count}")
```
输出结果为:
```
this: 1
is: 2
a: 1
sample: 1
article.: 1
it: 1
used: 1
to: 1
demonstrate: 1
word: 1
frequency: 1
counting: 1
in: 1
python.: 1
```
阅读全文
相关推荐










