Skip to content

Instantly share code, notes, and snippets.

@hellertime
Created July 6, 2012 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hellertime/3060604 to your computer and use it in GitHub Desktop.
Save hellertime/3060604 to your computer and use it in GitHub Desktop.
Python n-gram generator using itertools
import itertools
def ngrams(xs, f = None, n = 3):
ts = itertools.tee(xs, n)
for i, t in enumerate(ts[1:]):
for _ in xrange(i + 1):
next(t, None)
return map(f, itertools.izip(*ts))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment