How to split a string into n-grams in Python

N-grams are groups of words that follow one another. For example, splitting “this is a sentence” into 2-grams results in (“this”, “is”), (“is”, “a”), and (“a”, “sentence”).

Solution for How to split a string into n-grams in Python : You can use nltk.ngrams() to generate n-grams from a sequence of items Call nltk.ngrams(sequence, n) with a list as sequence and an integer as n to return a generator. Iterate through the generator to print the n-grams.


how-to-split-a-string-into-n-grams-in-python