这个程序中的语法错误在哪里?

时间:2015-04-02 07:55:43

标签: 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:
        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)

2 个答案:

答案 0 :(得分:0)

改变这个:

print(uppercasecount),(lowercasecount),(digitcount)

为:

print uppercasecount,lowercasecount,digitcount

而不是readlines,请使用read

for character in infile.read():

readlines会将整个文件读作行列表

read将整个文件作为字符串

读取

答案 1 :(得分:0)

python 23的完整答案。如果您想要计算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))