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>You can use a 2 line <a href="https://docs.python.org/2.7/library/collections.html#collections.deque" rel="nofollow">deque</a> and a <a href="https://docs.python.org/2.7/library/collections.html#collections.Counter" rel="nofollow">Counter</a>:</p>

<pre><code>from collections import Counter, deque

lc=Counter()
d=deque(maxlen=2)
with open(fn) as f:
    d.append(next(f))
    for line in f:
        d.append(line)
        lc+=Counter(["{},{}".format(*[e.rstrip() for e in d])])

&gt;&gt;&gt; lc
Counter({'fff,err': 2, 'ddd,fff': 1, 'bob,fff': 1, 'aaa,bob': 1, 'err,ddd': 1})
</code></pre>

<p>You can also use a <a href="https://regex101.com/r/uA0oG2/1" rel="nofollow">regex</a> with a capturing look ahead:</p>

<pre><code>with open(fn) as f:
    lc=Counter((m.group(1)+','+m.group(2),) for m in re.finditer(r"(\w+)\n(?=(\w+))", f.read()))
</code></pre>

python dictionary iterator generator