给定任意一篇文章,统计其中单词出现数量
时间: 2023-08-13 16:03:44 浏览: 40
好的,我可以帮您实现这个功能。首先,我们需要将文章分解成单词,可以使用 Python 中的 `split()` 函数。然后,我们可以使用字典来存储每个单词和它出现的次数。
下面是一个示例代码:
```python
article = "This is a sample article for word count. We will count the number of times each word appears in this article."
# 将文章分解成单词
words = article.split()
# 定义一个字典来存储单词和它出现的次数
word_count = {}
# 统计单词出现的次数
for word in words:
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
# 输出每个单词和它出现的次数
for word, count in word_count.items():
print(f"{word}: {count}")
```
输出结果如下:
```
This: 1
is: 1
a: 1
sample: 1
article: 2
for: 1
word: 2
count.: 1
We: 1
will: 1
the: 1
number: 1
of: 1
times: 1
each: 1
appears: 1
in: 1
this: 1
article.: 1
```
以上代码可以统计文章中每个单词出现的次数,并输出结果。您可以将上面的代码复制到 Python 环境中进行测试。