Vahideh Vahideh - 4 months ago 13
Python Question

printing 5 words before and after a specific word in a file in python

I have a folder which contains some other folders and these folders contain some text files. (The language is Persian). I want to print 5 words before and after a keyword with the keyword in the middle of them. I wrote the code, but it gives the 5 words in the start and the end of the line and not the words around the keyword. How can I fix it?

Hint: I just write the end of the code which relates to the question above. The start of the code is about the opening and normalizing the files.

def c ():
y = "آرامش"
text= normal_text(folder_path) # the first function to open and normalize the files
for i in text:
for line in i:
if y in line:
z = line.split()
print (z[-6], z[-5],
z[-4], z[-3],
z[-2], z[-1], y,
z[+1], z[+2],
z[+3], z[+4],
z[+5], z[+6])


what I expect is something like this:

word word word word word keyword word word word word word

Each sentence in a new line.

Answer
def c():
    y = "آرامش"
    text= normal_text(folder_path) # the first function to open and normalize the files
    for i in text:
        for line in i:
            split_line = line.split()
            if y in split_line:
                index = split_line.index(y)
                print (' '.join(split_line[max(0,index-5):min(index+6,le
n(split_line))]))

Assuming the keyword must be an exact word.