Skip to main content
 首页 » 编程设计

python之在python中计算文本文件中的字母

2025年05月04日29txw1958

所以我正在尝试做这道题

编写一个程序,读取名为 text.txt 的文件并将以下内容打印到 屏幕:

 该文件中的字符数

 该文件中的字母数

 该文件中大写字母的数量

 该文件中的元音数量

到目前为止我已经得到了这个,但是我卡在了第 2 步,这就是我到目前为止得到的。

file = open('text.txt', 'r') 
lineC = 0 
chC = 0 
lowC = 0 
vowC = 0 
capsC = 0 
for line in file: 
    for ch in line: 
        words = line.split() 
        lineC += 1 
        chC += len(ch) 
for letters in file: 
        for ch in line: 
print("Charcter Count = " + str(chC)) 
print("Letter Count = " + str(num)) 

请您参考如下方法:

您可以使用正则表达式来做到这一点。查找您的模式的所有出现作为您的列表,然后查找该列表的长度。

import re 
with open('text.txt') as f: 
    text = f.read() 
    characters = len(re.findall('\S', text)) 
    letters = len(re.findall('[A-Za-z]', text)) 
    uppercase = len(re.findall('[A-Z]', text)) 
    vowels = len(re.findall('[AEIOUYaeiouy]', text))