import nltk
import re

with open("Emma_Austen.txt") as file:
    txt = file.read()

list_of_tokens = re.findall(r'\b\w[\w-]*\b', txt.lower())

def make_conc(word_to_conc, list_to_find_in, context_to_use, conc_list):
    """Creates a concordance as a list given a word / phrase
    word_to_conc - The word to find in the text
    list_to_find_in - The tokenized text to find the word
    context_to_use - Number of words to show before and after the keyword.
    conc_list - The container of concordances
    """
    end = len(list_to_find_in) # get length of the text
    for location in range(end):
        if list_to_find_in[location] == word_to_conc:
            # Here we check whether we are at the very beginning or end
            if (location - context_to_use) &lt; 0:
                begin_conc = 0 # cannot get any word appearing before
            else:
                begin_conc = location - context_to_use
                
            if (location + context_to_use) &gt; end:
                end_conc = end # cannot get any words after keyword
            else:
                end_conc = location + context_to_use + 1
            
            # extract from the text from the given start and end points
            # of the tokens
            the_context = (list_to_find_in[begin_conc:end_conc])
            conc_line = ' '.join(the_context)
            conc_list.append("{}: {}".format(location, conc_line))
            
# set a word to find
word_to_find = 'emma'

# set the context of words on either side to grab
context = 5

# create a list to store the concordance
conc_list = []

make_conc(word_to_find, list_of_tokens, context, conc_list)
# get the last 5 items of the concordance list
print(conc_list[-5:])