v9.1.1
Menu

Context Window Extractor

easyPROQuestion AnsweringNLP 3: Advanced

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

Input
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
Output
[(0, 'deep learning is a subset of machine learning'), (2, 'machine translation converts text between languages'), (3, 'learning algorithms improve with data')]
Reasoning
  • Inputs: query is machine learning, so the query words are Q={machine,learning}Q = \{\text{machine}, \text{learning}\}. sentences holds 4 strings, numbered 0 to 3 by position.
  • Each sentence is broken into its whole words SiS_i, and it is kept exactly when Q∩Si≠∅Q \cap S_i \neq \varnothing, 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

Learn this in

More from NLP 3: Advanced

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.