rowana rowana - 2 months ago 41
Python Question

TypeError: str object is not an iterator

I have a file consisting of words, one word on each line. The file looks like this:

aaa
bob
fff
err
ddd
fff
err


I want to count the frequency of the pair of words which occur one after the other.

For example,

aaa,bob: 1
bob,fff:1
fff,err:2


and so on.
I have tried this

f=open(file,'r')
content=f.readlines()
f.close()
dic={}
it=iter(content)
for line in content:
print line, next(line);
dic.update({[line,next(line)]: 1})


I got the error:

TypeError: str object is not an iterator


I then tried using an iterator:

it=iter(content)
for x in it:
print x, next(x);


Got the same error again.
Please help!

Answer

Your value x holds a string 'ddd/ccc/etc'. it has not next. next() belongs to the iterator and it used to get next element from the iterator. The correct way to call it is it.next()

it=iter(content)
for x in it:
    print x, it.next();

But you will get an exception after you finish to consume all elements in the iterator. So, you need to catch StopIteration exception.

it=iter(content)
for x in it:
    try:
        line, next_line =  x, it.next()
        #do your counting logic here
    except StopIteration:
        break
Comments