Skip to content

Instantly share code, notes, and snippets.

@farcaller
Created November 7, 2010 21:18
Show Gist options
  • Save farcaller/666855 to your computer and use it in GitHub Desktop.
Save farcaller/666855 to your computer and use it in GitHub Desktop.
Python one-liner to count words in a string
> s = 'foo bar baz baz'
> reduce(lambda x,y:dict([ (k, (lambda a,b,k:(a[k] + (1 if k in b else 0)))(x,y,k)) for k in x.keys()]+[ (k,1) for k in y.keys() if not k in x ]), map(lambda x: {x:1}, s.split()))
{'bar': 1, 'baz': 2, 'foo': 1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment