Question: Python Question I am working on a text file (called 84.txt) and it contains a book. I have created a function (called load_book) that reads

Python Question

I am working on a text file (called 84.txt) and it contains a book. I have created a function (called load_book) that reads the book and splits it into paragraphs. I now need to create another function called kwic(paragraphs, search_terms) that accepts a list of string paragraphs and a set of search_term strings. I will include the full question and code I have so far below.

Question:

Write a function called kwic(paragraphs, search_terms) that accepts a list of string paragraphs and a set of search_term strings. The function should:

  1. initialize data as a defaultdict of lists
  2. loop over the paragraphs and apply spacy's processing to produce a doc for each;
  3. loop over the doc.sents resulting from each paragraph;
  4. loop over the words in each sentence;
  5. check: if a word is in the search_terms set;
  6. if (5), then .append() the reference under data[word] as a list: [[i, j, k], sentence], where i, j, and k refer to the paragraph-in-book, sentence-in-paragraph, and word-in-sentence indices, respectively.

Your output, data, should then be a default dictionary of lists of the format:

data['word'] = [[[i, j, k], ["These", "are", "sentences", "containing", "the", "word", "'word'", "."]], ...,]

Note, we have imported spacy and set it up to use the "en" model. This will require you to install spacy by running pip install spacy and downloading the "en" model by running the command python -m spacy download en.

Code:

from collections import defaultdict import spacy nlp = spacy.load("en")

def kwic(paragraphs, search_terms = {}): #---Your code starts here---

#---Your code ends here--- return(data)

=======================================

Checking if code works:

kwic(paragraphs, {'Ocean', 'seas'})

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!