Python 这个程序的语法错误在哪里?
我用python创建的这个程序应该计算文本文件中大写字母、小写字母、数字和空白字符的数量。它总是带着语法错误返回。我很难找出我犯错误的原因Python 这个程序的语法错误在哪里?,python,python-2.7,Python,Python 2.7,我用python创建的这个程序应该计算文本文件中大写字母、小写字母、数字和空白字符的数量。它总是带着语法错误返回。我很难找出我犯错误的原因 infile = open("text.txt", "r") uppercasecount, lowercasecount, digitcount = (0, 0, 0) for character in infile.readlines(): if character.isupper() == True: uppercasec
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)
更改此项:
print(uppercasecount),(lowercasecount),(digitcount)
致:
使用“读取”代替“读取行”:
readlines将整个文件作为行列表读取
read将以字符串形式读取整个文件python 2和3的完整答案。如果你想得到字母而不是单词的数量,试试这个
将printuppercasecount、lowercasecount、digitcount更改为printuppercasecount、lowercasecount、digitcount。此外,readlines会为您提供一个列表。试试看,非常感谢。如果不太麻烦的话,你知道我如何在文件中添加空白字符的数量吗?使用计数器,非常感谢。如果没有太多问题的话,你知道我如何在文件中添加空白字符的数量吗?你想计算空白字符的数量吗?使用str.isspace作为空白
print uppercasecount,lowercasecount,digitcount
for character in infile.read():
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))