统计一篇文章中每个单词出现的次数
时间: 2023-09-10 14:15:08 浏览: 60
可以使用Python编程语言来实现这个功能。下面是一个简单的实现示例:
```python
# 打开文件并读取内容
with open('article.txt', 'r') as f:
content = f.read()
# 去除标点符号和换行符
content = content.replace('\n', ' ')
for punctuation in '.,?!;:()[]{}':
content = content.replace(punctuation, '')
# 将文章内容按空格分割成单词列表
words = content.split(' ')
# 统计每个单词出现的次数
word_count = {}
for word in words:
if word:
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}')
```
这段代码首先打开一个名为`article.txt`的文件,并将文件内容读取到一个字符串变量中。接下来,代码使用`replace()`方法去除文章中的标点符号和换行符,并使用`split()`方法将文章内容按空格分割成一个单词列表。然后,代码使用一个字典变量`word_count`来统计每个单词出现的次数。最后,代码遍历`word_count`字典,并输出每个单词出现的次数。