Context Window Extractor
Extract relevant context windows from a document for a given query.
Given a document (list of sentences) and a query, find sentences that contain at least one query word and return them with their indices.
Input: extract_context(query, sentences)
- query: query string (space-separated words, lowercase)
- sentences: list of N sentence strings (lowercase)
Output: A list of tuples (index, sentence) for sentences containing at least one query word. Matching is case-insensitive (both already lowercase).
Example
machine learning 4 deep learning is a subset of machine learning natural language processing uses rules machine translation converts text between languages learning algorithms improve with data
[(0, 'deep learning is a subset of machine learning'), (2, 'machine translation converts text between languages'), (3, 'learning algorithms improve with data')]
- Inputs:
queryismachine learning, so the query words are .sentencesholds 4 strings, numbered 0 to 3 by position. - Each sentence is broken into its whole words , and it is kept exactly when , i.e. it shares at least one word with the query.
- Sentence 0 contains both "learning" (twice) and "machine": kept, but only once. Sentence 1 ("natural language processing uses rules") shares nothing: dropped.
- Sentence 2 contains "machine": kept. Notice that only exact whole words count: a sentence like "machines are relearning fast" would be dropped, since neither "machines" nor "relearning" equals a query word.
- Sentence 3 contains "learning": kept.
- Output: a list of (index, sentence) pairs in original order, so indices 0, 2, 3 appear with their full, unchanged text. If no sentence shares a word with the query, the result is an empty list
[].
Constraints
- Match whole words only (split on whitespace)
- Both query and sentences are lowercase
- Return matches in order of appearance
- A sentence matches if it contains ANY query word