我的任务是计算 .txt
文件中的大写、小写、数字和空白字符。
我尝试了多种方法,但似乎不太正确。我不知道我要去哪里。
这是我得到的输出:
大写计数为0 小写计数为 0 位数为0 空白计数为 0
代码:
def main():
uppercase_count = 0
lowercase_count = 0
digits_count = 0
whitespace_count = 0
uppercase =['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
lowercase = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
digits = ['0','1','2','3','4','5','6','7','8','9']
whitespace = [' ']
infile = open("text.txt", "r")
data = infile.readlines()
for character in data:
if character in uppercase:
uppercase_count += 1
for character in data:
if character in lowercase:
lowercase_count += 1
for character in data:
if character in digits:
digits_count += 1
for character in data:
if character in whitespace:
whitespace_count += 1
print('The uppercase count is',uppercase_count)
print('The lowercase count is',lowercase_count)
print('The digit count is',digits_count)
print('The whitespace count is',whitespace_count)
main()
最佳答案
你可以简单地使用内置函数
for character in data:
if character.isupper():
uppercase_count += 1
elif character.islower():
lowercase_count += 1
elif character.isspace():
whitespace_count +=1
elif character.isdigit():
digit_count +=1
您也可以使用以下命令计算每一行的字符数。
digit_count,whitespace_count,lowercase_count,uppercase_count=0,0,0,0
lines = infile.readlines()
for data in lines:
for character in data:
if character.isupper():
uppercase_count += 1
elif character.islower():
lowercase_count += 1
elif character.isspace():
whitespace_count +=1
elif character.isdigit():
digit_count +=1
关于python - 计算文件中的大写字母、小写字母、数字和空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34126663/