统计文本文件中单词出现的个数
时间: 2023-11-13 13:03:06 浏览: 219
可以使用Python编程来实现统计文本文件中单词出现的个数,具体步骤如下:
1. 打开文件并读取文本内容
```python
with open("filename.txt", "r") as f:
text = f.read()
```
2. 将文本内容转换为单词列表
```python
words = text.split()
```
3. 创建一个字典,用于存储每个单词出现的次数
```python
word_count = {}
```
4. 遍历单词列表,统计每个单词出现的次数,并将结果存储在字典中
```python
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
```
5. 输出每个单词出现的次数
```python
for word, count in word_count.items():
print(f"{word}: {count}")
```
完整代码如下:
```python
with open("filename.txt", "r") as f:
text = f.read()
words = text.split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
for word, count in word_count.items():
print(f"{word}: {count}")
```
阅读全文