python - TypeError: str object is not an iterator -
i have file consisting of words, 1 word on each line. file looks this:
aaa bob fff err ddd fff err
i want count frequency of pair of words occur 1 after other.
for example,
aaa,bob: 1 bob,fff:1 fff,err:2
and on. have tried this
f=open(file,'r') content=f.readlines() f.close() dic={} it=iter(content) line in content: print line, next(line); dic.update({[line,next(line)]: 1})
i got error:
typeerror: str object not iterator
i tried using iterator:
it=iter(content) x in it: print x, next(x);
got same error again. please help!
you need keep track of previous line, file object returns own iterator don't need iter or readlines @ all, call next once @ start creating variable prev keep updating prev in loop:
from collections import defaultdict d = defaultdict(int) open("in.txt") f: prev = next(f).strip() line in map(str.strip,f): # python2 use itertools.imap d[prev, line] += 1 prev = line
which give you:
defaultdict(<type 'int'>, {('aaa', 'bob'): 1, ('fff', 'err'): 2, ('err', 'ddd'): 1, ('bob', 'fff'): 1, ('ddd', 'fff'): 1})
Comments
Post a Comment