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

标签 python python-3.x

所以我正在尝试做这道题

编写一个程序,读取名为 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))

关于python - 在python中计算文本文件中的字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36026798/

相关文章:

python - 1 个带有 Gunicorn 的 Web Worker 是否总是意味着只有 1 个进程?

python - X 的浮点精度

python-3.x - 如何将 Python 脚本输出重定向到 PyQT5 GUI 控制台,而无需单击任何按钮?

python - np.mean 的 Numba 失败

python - 这种链式比较真的可以像 PyCharm 声称的那样简化吗?

python - 用Python BeautifulSoup 抓取两种价格

python - Openpyxl 检查空单元格

python - 使用 Tkinter 按钮了解 Python Lambda 行为

python - 如何使用 Selenium 和 Python 3 查找 iframe

python - pytest 属性错误 : "function object has no attribute" when referencing fixture in Python 3