How to find words or sentences around the found word?

Viewed 58

How to find words next to the found word? I want to see the left word AND the right word of the found word x too.

I was able to extract the index of the found word in the sourcetext. But by doing sourcetext[sourceindex+1] it gives me just the letter of that word. It should give me the next word next to the found word. What am I doing wrong?

    sourcetext=browser.page_source
    searchword= ["hello","world","pretty","life"]
        
        
        for x in searchword:
      
            if x in sourcetext:
    
                sourceindex=sourcetext.index(x)
               
                print("FOUND!" + x + "  " + sourcetext[sourceindex+1])
                                   
            else:
                continue
         
3 Answers

You can use try and except

sourcetext=browser.page_source
searchword= ["hello","world","pretty","life"]
        
        
for x in searchword:
      
    if x in sourcetext:
    
        sourceindex=sourcetext.index(x)
        next_word=""
        i=1
        while True:
            try:
                if sourcetext[sourceindex+len(x)+i] !=" ":
                    next_word+=sourcetext[sourceindex+len(x)+i]
                else:
                    break
                i+=1
            except IndexError:
                break
        print("FOUND!" + x + "  " + next_word)

This is a simple solution and can be expanded to work with Selenium or Bs4.

sentence = "this is a six word sentence."
search = "six"

sentence = sentence.split(" ")

if search in sentence:
    my_index = sentence.index(search)
    word_before = my_index - 1
    word_after = my_index + 1

    print(sentence[word_before], search, sentence[word_after])

It works by splitting the original text into a list. The if statement takes a word or variable and checks if it is in the list, if it is it finds the index value of that word which is recorded in my_index. This can then be used to find the word before and after that word.

This can be a slow solution when larger texts are used.

If I understand correctly, you want to have the word to the left and right of the searchword. My approach here would be to use regex to find the words.

import re

for searchword in searchwords:
    match = re.search(r'(?:(\w*)\s)?{}(?:\s(\w*))?'.format(searchword), sourcetext)
    if match:
        print('{} is between {} and {}'.format(searchword, match.group(1), match.group(2)))

This solution should work quite well for long texts. For example, if there is no word on the left side, group(1) = None and you can query it easily.

Related