Skip to content Skip to sidebar Skip to footer

How Can I Search Within A Document For A Keyword And Then Subsequent Key Words Within A Set Number Of Lines Of The Original Keyword In Python?

I want to search for a key word in a document and then check to see whether that keyword is within 5 lines of another key word. If it is, I want to print the line and the followin

Solution 1:

Instead of

"Financial Assets:"in searchlines[m-5:m+5]

You need to have:

any("Financial Assets:"in line2 for line2 in searchlines[m-5:m+5])

Your original code looks for a line which contains exactly the content "Financial Assets:", instead of looking for it as a substring in each line.

Solution 2:

The expression

"carrying"in line

searches the string in any position inside the line. However the statement

"Finantial Assets:"in searchlines[m-5:m+5]

is searching for an exact match (i.e. a line that's exactly `"Finantial Assets:") in that sublist. You need to change this second part to something like

"Finantial Assets:"in" ".join(searchlines[m-5:m+5])

Post a Comment for "How Can I Search Within A Document For A Keyword And Then Subsequent Key Words Within A Set Number Of Lines Of The Original Keyword In Python?"