How to match value in enumeration to a keyword?

Viewed 101

I want to write a keyword-in-context script in which I first read a text file as an enumerated list and then return a given keyword and the five next words.

I saw that similar questions were asked for C# and I found solutions for the enum module in Python, but I hope there is a solution for just using the enumerate() function.

This is what I have got so far:

# Find keywords in context

import string

# open input txt file from local path

with open('C:\\Users\\somefile.txt', 'r', encoding='utf-8', errors='ignore') as f: # open file
    data1=f.read() # read content of file as string
    data2=data1.translate(str.maketrans('', '', string.punctuation)).lower() # remove punctuation
    data3=" ".join(data2.split()) # remove additional whitespace from text
    indata=list(data3.split()) # convert string to list
    print(indata[:4])
    
searchterms=["text", "book", "history"]
 
def wordsafter(keyword, source):
    for i, val in enumerate(source):
        if val == keyword: # cannot access the enumeration value here
            return str(source[i+5]) # intend to show searchterm and subsequent five words
        else:
            continue

for s in searchterms: # iterate through searchterms
    print(s)
    wordsafter(s, indata)
    
print("done")

I was hoping I could simply access the value of the enumeration like I did here, but that does not seem to be the case.

1 Answers

With credits to @jasonharper, your improved code:

import string


def wordsafter(keyword, source):
    for i, val in enumerate(source):
        if val == keyword:
            return ' '.join(source[i:i + 5])  # intend to show searchterm and subsequent five words

# wordsafter() for all instances
def wordsafter(keyword, source):
     instances = []
     for i, val in enumerate(source):
        if val == keyword:
            instances.append(' '.join(source[i:i + 5]))
     return instances

# open input txt file from local path
with open('README.md', 'r', encoding='utf-8', errors='ignore') as f:  # open file
    data1 = f.read()  # read content of file as string
    data2 = data1.translate(str.maketrans('', '', string.punctuation)).lower()  # remove punctuation
    data3 = " ".join(data2.split())  # remove additional whitespace from text
    indata = list(data3.split())  # convert string to list

searchterms = ["this", "book", "history"]
for string in searchterms:  # iterate through searchterms
    result = wordsafter(string, indata)
    if result:
        print(result)
Related