我在python中创建的程序应该计算文本文件中大写字母,小写字母,数字和空格字符数。它不断回来语法错误。我无法找出错误的原因。
infile = open("text.txt", "r")
uppercasecount, lowercasecount, digitcount = (0, 0, 0)
for character in infile.readlines():
if character.isupper() == True:
uppercasecount += 1
if character.islower() == True:
lowercasecount += 1
if character.isdigit() == True:
digitcount += 1
print(uppercasecount),(lowercasecount),(digitcount)
print "Total count is %d Upper case, %d Lower case and %d Digit(s)" %(uppercasecount, lowercasecount, digitcount)
答案 0 :(得分:0)
改变这个:
print(uppercasecount),(lowercasecount),(digitcount)
为:
print uppercasecount,lowercasecount,digitcount
而不是readlines
,请使用read
:
for character in infile.read():
readlines
会将整个文件读作行列表
read
将整个文件作为字符串
答案 1 :(得分:0)
python 2
和3
的完整答案。如果您想要计算letters
而不是words
infile = open("text.txt", "r")
uppercasecount, lowercasecount, digitcount = (0, 0, 0)
for character in infile.read():
if character.isupper() == True:
uppercasecount += 1
if character.islower() == True:
lowercasecount += 1
if character.isdigit() == True:
digitcount += 1
print(uppercasecount,lowercasecount,digitcount)
print("Total count is %d Upper case, %d Lower case and %d Digit(s)" %(uppercasecount, lowercasecount, digitcount))