Search code examples
pythontypeerrortraceback

Getting error trying to count occurences of each letter from file


I am trying to create a program which counts the occurrences of each letter from text pulled from another file. I haven't got too far with it yet, I just ran my first test for letter A and am not able to go further. This was my first attempt at assigning multiple variables to a single value, is this where my error occurred? Here is my code, go easy, I'm not very good at this stuff, but I'm trying to learn.

    file = open('words.txt', 'r')
    A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z = 0

    def LetterA():
        for line in file:
            words = line.split()
            for i in words:
                for letter in i:
                    if(letter == a) or (letter == A):
                        A = A + 1
        return A
    LetterA()

    print(A)

Here is my error print out:

    Traceback (most recent call last):
      File "D:/Python/twentysecondprogram.py", line 2, in <module>
        A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z = 0
    TypeError: cannot unpack non-iterable int object

Solution

  • I'm new at python, so don't blame me if I'm wrong :))

    1. I think your variable is out of scope.

    Try this.

        def letter_A():
        letterA = 0
        for line in file:
            words = line.split()
            for i in words:
                for letter in i:
                    if(letter == 'a') or (letter == 'A'):
                        letterA += 1
        print(letterA)
    
    
    letter_A()
    

    Good Luck!