打开一个英文的文本文件,统计原文中每个英文单词出现的次数
时间: 2023-12-20 18:04:24 浏览: 68
以下是Python代码实现:
```python
import string
# 读取文件内容
with open('filename.txt', 'r') as f:
content = f.read()
# 去除标点符号并转换为小写
content = content.translate(str.maketrans('', '', string.punctuation)).lower()
# 按空格划分单词
words = content.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}")
```
其中,`filename.txt`是要统计的文件名,可以根据实际情况进行修改。这段代码会输出每个单词及其出现次数。
相关问题
统计一个英文文本文件所有单词出现次数python
可以使用Python中的collections模块中的Counter类来实现。以下是一个简单的示例代码:
```python
import collections
# 打开文本文件并读取内容
with open('text_file.txt', 'r') as file:
text = file.read()
# 将文本分割为单词并统计出现次数
word_counts = collections.Counter(text.split())
# 输出结果
for word, count in word_counts.items():
print(f'{word}: {count}')
```
在上面的代码中,我们首先打开并读取了一个文本文件。然后使用split()方法将文本分割为单词,并使用Counter类统计每个单词出现的次数。最后,我们遍历计数器的每个元素并输出单词及其出现次数。
python统计文件文本中每个单词出现次数
可以使用Python中的字典(dictionary)来统计每个单词出现的次数,具体实现步骤如下:
1. 读取文件内容,将文本内容存储在一个字符串变量中。
2. 将字符串变量中的所有标点符号和换行符替换为空格。
3. 将字符串变量按照空格分割成一个列表。
4. 遍历列表,统计每个单词出现的次数,将其存储在一个字典中。
5. 打印出字典中每个键值对,即每个单词出现的次数。
下面是代码实现:
```python
# 打开文件,并读取文件内容
with open('filename.txt', 'r') as f:
content = f.read()
# 将标点符号和换行符替换为空格
content = content.replace(',', ' ').replace('.', ' ').replace('\n', ' ')
# 将字符串按照空格分割成一个列表
words = content.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('{0}: {1}'.format(word, count))
```
其中,`filename.txt` 是要统计的文件名。这个脚本会输出每个单词出现的次数。