我的任务是计算.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()
答案 0 :(得分:3)
你可以简单地使用内置功能
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
答案 1 :(得分:2)
您正在逐行阅读,而不是char
,所以您通过read
将其作为整个字符串阅读,并且最好将所有for
个循环分组这样做:
data = infile.read()
for character in data:
if character in uppercase:
uppercase_count += 1
elif character in lowercase:
lowercase_count += 1
elif character in digits:
digits_count += 1
elif character in whitespace:
whitespace_count += 1
编辑:
此外,您没有理由在列表中存储所有upper-case
,lower-case
,digits
和white space
个字符,请使用{{1} }模块,已经准备好了所有这些:
string
更好的方法是使用内置方法:
isupper(),islower()..您可以检查它们here。
答案 2 :(得分:1)
data = infile.read()
请勿阅读lines
,而是将整个字符串作为整个字符串阅读。如果您阅读character
行line
,则可能需要character
答案 3 :(得分:0)
data = infile.read()
value = [ i for i in data]
upper = len(list(filter(lambda x: x.isupper(), value)))
digit = len(list(filter(lambda x: x.isdigit(), value)))
space = len(list(filter(lambda x: x.isspace(), value)))