Home > OS >  Print previous word after finding a match in text
Print previous word after finding a match in text

Time:03-27

So i need a way to have python find a match for a string and then find the previous word. For example:

If I search for 'abc':

123 xyz abc def

I get:

xyz abc

The full text im searching through is a requests response if that helps/changes anything.

I tried to write something to select the previous line, but it just never happened. I deleted the code (which i shouldnt have done) since it didnt work.

CodePudding user response:

You could also just use a simple list comprehension:

string = input('Enter string to be searched:').split(' ')
search = input('Enter characters to be searched for in string:')
output = ''.join([string[i-1]   ' '   string[i] for i in range(len(string)) if string[i] == search])
if len(output) == 0:
    print('No matches found')
else:
    print('Match found: '   output)

Output:

Enter string to be searched: 123 xyz abc def
Enter characters to be searched for in string: abc
Match found: xyz abc

CodePudding user response:

One way to do this would be using a regex to match the abc and capture the word before it at the same time:

import re

s = '123 xyz abc def'
m = re.search(r'(\w \s abc)', s)
if m is not None:
    print(m.group())

Output:

xyz abc

If abc might occur at the beginning of the string, and you still want to match, you could change the regex to allow for a match at the beginning as well:

s = 'abc def'
m = re.search(r'((\w \s |^)abc)', s)
if m is not None:
    print(m.group())

Output:

abc

Note you can use re.findall rather than re.search to simplify the code e.g.

m = re.findall(r'((?:\w \s |^)abc)', s)

m will be a list of all matches in the string (empty if there were none).

CodePudding user response:

Get a list of words (assuming they are separated with white spaces):

s = "123 xyz abc def"
words = s.split()

Zip this list with itself shifted by one position forward, and build a dictionary where the next word is a key and the preceding word is a value:

word_dict = dict(zip(words[1:], words))
# {'xyz': '123', 'abc': 'xyz', 'def': 'abc'}

Look up the word in the dictionary:

word_dict['abc']
#'xyz'

Limitation: the solution does not work if you have more than one instance of the word of interest in the string.

  • Related