2014-03-27 68 views
0

我似乎无法得到此python程序的工作。它应该从我桌面上的用户那里获得一个输入的.txt文件。 txt文件作为一行字符。用户输入文件后,程序应计算Xs,Ys和Zs(大写和小写)的数量以及不是Xs,Ys或Zs的“坏”字符的数量。从用户输入的txt文件中读取文件和计数字符

这是我有:

def main(): 
    count = 0 
    F1 = raw_input("Enter output file name: ") 
    File = open(F1,"r") 
    for i in File: 
     a=str.count('x' and 'X') 
     print "The number of Xs was: ", a 
     b= str.count('y' and 'Y') 
     print "The number of Ys was: ", b 
     c = str.count('z' and 'Z') 
     print "The number of Zs was: ", c 
     d = str.count 
     print "The number of bad characters was: ", 
    return 

main() 

回答

1

这种表达

str.count('x' and 'X') 

不会做你的想法。见子表达式'x' and 'X'如何评估:

>>> 'x' and 'X' 
'X' 

你可以这样做,而不是:

a=str.count('x') + str.count('X') 

a=s.upper().count('X') 

你有固定的A,B和C的计算之后,您需要确定d的计算。可以做这样的:

d = len(str) - (a + b + c) 
+0

非常感谢!但我仍然得到这个错误,我仍然需要一种方法来计算所有的坏字符: 回溯(最近呼叫最后): 文件“C:\ Users \ Desktop \ lab8.py”,第16行,在 main() 文件“C:\ Users \ Desktop \ lab8.py”,第6行,主要为 a = str.count('x')+ str.count('X') TypeError:count )至少需要1个参数(0给出) – user3317056

+0

查看更新后的答案。 – piokuc

0

您需要i.count更换str.count你做了之后@piokuc说什么。

这是因为它包含你的字符串,而不是str。