mrw
mrw

Reputation: 23

python argument of type 'int' is not iterable when using for in

I am trying to write code that will accept a filename from the command line and print out the following properties:

I keep getting the error message

"argument of type 'int' is not iterable"

for the line if 'the' in words:.

How do I fix this?

import sys
import string

file_name=sys.argv[0]

char= words = lines = theCount = aCount= 0

with open(file_name,'r') as in_file:
    for line in in_file:
        lines +=1
        words +=len(line.split())
        char +=len(line)
        if 'the' in words:
            theCount +=1
        if 'a' in words:
            a +=1
        if 'an' in words:
            a +=1

print("Filename:", file_name)
print("Number of lines:", lines)
print("Number of characters:", char)
print("Number of 'the'", theCount)
print("Number of a/an:", aCount)

Upvotes: 0

Views: 556

Answers (2)

am05mhz
am05mhz

Reputation: 2875

there are some errors in your code, read the comments in this snipped:

import sys
#import string   #not sure if this is needed

file_name=sys.argv[0]

char= words = lines = theCount = aCount= 0


with open(file_name,'r') as in_file:
    for line in in_file:
        lines +=1
        x = line.split() #use a variable to hold the split words
                         #so that you can search in it
        words +=len(x)
        char +=len(line)
        if 'the' in x:   #your original code was using "words" variable
                         #that holds the "number of words" in the line,
                         #therefore ints are not iterable
            theCount +=1
        if 'a' in x:
            aCount +=1   #your original code using "a" variable 
                         #which did not initialized, 
                         #you have initialized "aCount" variable
        if 'an' in x:
            aCount +=1   #same as above

print("Filename:", file_name)
print("Number of lines:", lines)
print("Number of characters:", char)
print("Number of 'the'", theCount)
print("Number of a/an:", aCount)

https://repl.it/Mnwz/0

Upvotes: 0

Lawrence D'Oliveiro
Lawrence D'Oliveiro

Reputation: 2774

If you are trying to collect the actual words, rather than just the count of them, then perhaps you need to initialize words to an empty list:

words = []

and change

words += len(line.split())

to

words += line.split()

Upvotes: 0

Related Questions