如何用pycharm读取txt文件中的文字出现次数并且打印
时间: 2024-03-09 18:50:08 浏览: 86
可以使用Python中的内置函数和模块来实现读取txt文件中的文字出现次数并打印。以下是一个示例代码:
```python
# 打开文件
with open('file.txt', 'r') as file:
# 读取文件中的所有内容
data = file.read()
# 将所有的大写字母转换为小写字母
data = data.lower()
# 使用split()函数将字符串分割为单词列表
words = data.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}")
```
在上面的代码中,我们使用了Python内置函数`open()`来打开一个txt文件,并使用`read()`方法读取了其中的内容。然后,我们将所有的大写字母转换为小写字母,并使用`split()`函数将字符串分割为单词列表。接下来,我们初始化了一个空字典用于存储每个单词的出现次数,并遍历单词列表并统计每个单词的出现次数。最后,我们遍历字典并打印每个单词出现的次数。
相关问题
用pycharm编写一个程序实现如下功能:读入一个文本文件,统计在该文本文件中每个英文单词出现的频率,并输出单词频率最 高的 100 个单词。其中,单词的定义是连续的若干个小写英文字母。
好的,我明白了。以下是实现该功能的 Python 代码:
```python
import re
from collections import Counter
# 打开文本文件并读取
with open('text_file.txt', 'r') as f:
text = f.read()
# 使用正则表达式匹配连续的小写英文字母
words = re.findall(r'\b[a-z]+\b', text.lower())
# 统计单词出现的频率
word_counts = Counter(words)
# 打印出现频率最高的 100 个单词
for word, count in word_counts.most_common(100):
print(word, count)
```
其中,`text_file.txt` 是要统计的文本文件名。该程序使用正则表达式匹配单词,忽略大小写,并使用 `collections` 模块的 `Counter` 类来统计单词出现的频率。最后打印出现频率最高的 100 个单词及其出现次数。
阅读全文
相关推荐









