用python计算文本文件中的字母

2024-09-24 04:30:01 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试着解决这个问题

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

该文件中的字符数

该文件中的字母数

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

该文件中元音的数量

到目前为止,我已经做到了,但我被困在第二步,这是我目前为止得到的。在

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))

Tags: 文件in文本程序txtfor数量count
2条回答

您可以使用正则表达式来执行此操作。找到所有出现的模式作为列表,然后找到该列表的长度。在

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))

上面的答案使用正则表达式,如果您以前没有使用过正则表达式,那么这些表达式非常有用,值得学习。Bunji的代码也更高效,因为在Python中遍历字符串中的字符相对较慢。在

但是,如果您只想尝试使用Python来实现这一点,请查看下面的代码。有几点:首先,将您的open()包装在using语句中,完成后它将自动调用文件上的close()。接下来,请注意Python允许您以各种有趣的方式使用in关键字。任何序列都可以是“in-ed”,包括字符串。如果愿意,可以用自己的字符串替换所有string.xxx行。在

import string

chars = []

with open("notes.txt", "r") as f:
    for c in f.read():
        chars.append(c)


num_chars = len(chars)

num_upper = 0;
num_vowels = 0;
num_letters = 0

vowels = "aeiouAEIOU"
for c in chars:
    if c in vowels:
        num_vowels += 1
    if c in string.ascii_uppercase:
        num_upper += 1
    if c in string.ascii_letters:
        num_letters += 1

print(num_chars)
print(num_letters)
print(num_upper)
print(num_vowels)

相关问题 更多 >