Combine word pairs: python

I wrote a cartographer who prints pairs of words and the number 1 for each of them.

import sys from itertools import tee for line in sys.stdin: line = line.strip() words = line.split() def pairs(lst): return zip(lst,lst[1:]+[lst[0]]) for i in pairs(words): print i,1 

I tried to write a reducer that creates a dictionary, but I'm a little fixated on how to sum them up.

 import sys mydict = dict() for line in sys.stdin: (word,cnt) = line.strip().split('\t') #\t mydict[word] = mydict.get(word,0)+1 for word,cnt in mydict.items(): print word,cnt 

But it says that the arguments in the .split line are not enough, thoughts? Thanks.

0
source share
1 answer

I think the problem (word,cnt) = line.strip().split('\t') #\t
The split() method returns a list and tries to assign it (word, cnt) , which does not work, because the number of elements does not match (maybe sometimes there is only one word).
Maybe you want to use something like

 for word in line.strip().split('\t'): mydict[word] = mydict.get(word, 0) + 1 

If you have problems with empty list items, use list(filter(None, list_name)) to remove them.

Disclaimer: I have not tested the code. In addition, this only applies to your second example.

0
source

All Articles