N-Gram Generator
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
I love natural language processing 2
[('I', 'love'), ('love', 'natural'), ('natural', 'language'), ('language', 'processing')]- Input:
textis a sentence whose words are separated by whitespace, andnis how many consecutive words each n-gram holds. Here the text has words:I,love,natural,language,processing, and . - Math: the n-gram starting at word is the ordered group . It only exists if its last word is still inside the text, so runs from to , where is the word count.
- With and there are bigrams: .
- 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 words, so every middle word appears twice. For the count drops to , and for 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