Return an iterable of ngrams of length `ngram_length` given an `iterable`. Each ngram is a tuple of `ngram_length` items. The returned iterable is empty if the input iterable contains less than `ngram_length` items. Note: this is a fairly arcane but optimized way to compute ng
(iterable, ngram_length)
| 373 | |
| 374 | |
| 375 | def ngrams(iterable, ngram_length): |
| 376 | """ |
| 377 | Return an iterable of ngrams of length `ngram_length` given an `iterable`. |
| 378 | Each ngram is a tuple of `ngram_length` items. |
| 379 | |
| 380 | The returned iterable is empty if the input iterable contains less than |
| 381 | `ngram_length` items. |
| 382 | |
| 383 | Note: this is a fairly arcane but optimized way to compute ngrams. |
| 384 | |
| 385 | For example: |
| 386 | >>> list(ngrams([1,2,3,4,5], 2)) |
| 387 | [(1, 2), (2, 3), (3, 4), (4, 5)] |
| 388 | |
| 389 | >>> list(ngrams([1,2,3,4,5], 4)) |
| 390 | [(1, 2, 3, 4), (2, 3, 4, 5)] |
| 391 | |
| 392 | >>> list(ngrams([1,2,3,4], 2)) |
| 393 | [(1, 2), (2, 3), (3, 4)] |
| 394 | |
| 395 | >>> list(ngrams([1,2,3], 2)) |
| 396 | [(1, 2), (2, 3)] |
| 397 | |
| 398 | >>> list(ngrams([1,2], 2)) |
| 399 | [(1, 2)] |
| 400 | |
| 401 | >>> list(ngrams([1], 2)) |
| 402 | [] |
| 403 | |
| 404 | This also works with arrays or tuples: |
| 405 | |
| 406 | >>> from array import array |
| 407 | >>> list(ngrams(array('h', [1,2,3,4,5]), 2)) |
| 408 | [(1, 2), (2, 3), (3, 4), (4, 5)] |
| 409 | |
| 410 | >>> list(ngrams(tuple([1,2,3,4,5]), 2)) |
| 411 | [(1, 2), (2, 3), (3, 4), (4, 5)] |
| 412 | """ |
| 413 | return zip(*(islice(iterable, i, None) for i in range(ngram_length))) |
| 414 | |
| 415 | |
| 416 | def select_ngrams(ngrams, with_pos=False): |
no outgoing calls