TypeError: str object is not an iterator
<p>I have a file consisting of words, one word on each line. The file looks like this:</p>

<pre><code>aaa
bob
fff
err
ddd
fff
err
</code></pre>

<p>I want to count the frequency of the pair of words which occur one after the other.</p>

<p>For example,</p>

<pre><code>aaa,bob: 1
bob,fff:1
fff,err:2
</code></pre>

<p>and so on.
 I have tried this</p>

<pre><code>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})
</code></pre>

<p>I got the error: </p>

<pre><code>TypeError: str object is not an iterator
</code></pre>

<p>I then tried using an iterator:</p>

<pre><code>it=iter(content)
for x in it:
    print x, next(x);
</code></pre>

<p>Got the same error again. 
Please help!</p>

<p>As others mentioned, you can't use <code>next</code> on a line which is an string. You can use <code>itertools.tee</code> to create two independent iterator from your file object, then use <code>collections.Counter</code> and <code>zip</code> to create a counter object from the pairs of lines</p>

<pre><code>from itertools import tee
from collections import Counter
with open('test.txt') as f:
    # f = (line.rstrip() for line in f) # if you don't want the trailing new lines 
    f, ne = tee(f)
    next(ne)
    print(Counter(zip(f, ne)))
</code></pre>

<p>note that since file object is contain the lines with new-line at their trailing, if you don't want that you can strip the lines. </p>

python dictionary iterator generator