v9.1.1
Menu

N-Gram Generator

easyFREEText ProcessingNLP 1: Foundations

Generate word-level n-grams from a given text.

An n-gram is a contiguous sequence of n items from a given text. For word-level n-grams, the items are words.

Function: generate_ngrams(text, n)

  • text: the input string
  • n: the size of each n-gram (integer)

Output: A list of tuples, where each tuple contains n consecutive words.

Example:

  • Text: "I love natural language processing"
  • n = 2 (bigrams)
  • Output: [('I', 'love'), ('love', 'natural'), ('natural', 'language'), ('language', 'processing')]

Note: Do NOT lowercase the words — preserve original casing.

Example

Input
I love natural language processing
2
Output
[('I', 'love'), ('love', 'natural'), ('natural', 'language'), ('language', 'processing')]
Reasoning
  • Input: text is a sentence whose words are separated by whitespace, and n is how many consecutive words each n-gram holds. Here the text has 55 words: w1=w_1 = I, w2=w_2 = love, w3=w_3 = natural, w4=w_4 = language, w5=w_5 = processing, and n=2n = 2.
  • Math: the n-gram starting at word kk is the ordered group (wk,wk+1,…,wk+n−1)(w_k, w_{k+1}, \dots, w_{k+n-1}). It only exists if its last word wk+n−1w_{k+n-1} is still inside the text, so kk runs from 11 to L−n+1L - n + 1, where LL is the word count.
  • With L=5L = 5 and n=2n = 2 there are 5−2+1=45 - 2 + 1 = 4 bigrams: (w1,w2),(w2,w3),(w3,w4),(w4,w5)(w_1, w_2), (w_2, w_3), (w_3, w_4), (w_4, w_5).
  • Output: those tuples in order of starting position, casing preserved: [('I', 'love'), ('love', 'natural'), ('natural', 'language'), ('language', 'processing')].
  • Notice that neighbouring n-grams overlap in n−1n - 1 words, so every middle word appears twice. For n=3n = 3 the count drops to 33, and for n=1n = 1 each word becomes its own one-element tuple.

Constraints

  • Input text contains at least n words
  • 1 <= n <= 5
  • Words are split on whitespace
  • Preserve original casing
  • Output is a list of tuples

Learn this in

More from NLP 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.