user3317056
user3317056

Reputation: 37

Read a File and Count Characters from an inputted txt file from user

I can't seem to get this python program to work. It's supposed to get an inputted .txt file from the user which is on my desktop. The txt file as a single line of characters. After the user inputs the file, the program is then supposed to count the number of Xs, Ys, and Zs (both upper and lower case) and the number of "bad" characters that aren't Xs, Ys, or Zs.

Here's what I have:

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()

Upvotes: 0

Views: 83

Answers (2)

trevor
trevor

Reputation: 404

You need to replace str.count with i.count after you have done what @piokuc says.

This is because it contains your string, not str.

Upvotes: 0

piokuc
piokuc

Reputation: 26204

This expression

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

does not do what you think. See how the subexpression 'x' and 'X' evaluates:

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

You can do this, instead:

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

or

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

After you have fixed calculation of a,b and c, you need to fix calculation of d. Can be done like this:

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

Upvotes: 1

Related Questions