📘
N-Gram Generator
EasyText Processing
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.
Input format:
- Line 1: The text string
- Line 2: The value of n (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:
Step 1: Split text into words ["I", "love", "natural", "language", "processing"] — 5 words total
Step 2: Generate bigrams (n=2) We slide a window of size 2 across the word list:
- Position 0: ("I", "love")
- Position 1: ("love", "natural")
- Position 2: ("natural", "language")
- Position 3: ("language", "processing")
Total bigrams = 5 - 2 + 1 = 4
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
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.