Home > Software engineering >  Finding the next and previous word after keyword
Finding the next and previous word after keyword

Time:11-21

I'm looking at getting the immediate word before and after a keyword in a string.

text =  "I currently live in Chicago but  work in DC"
keywords = 'live in'
before_keyword, keyword, after_keyword = text.partition(keywords)
print (after_keyword)

Output here will be "Chicago but work in DC". before_keyword output is "I currently". How can I get only the immediate term before and after the keyword? i.e. "currently" for before_keyword and "Chicago" in after_keyword.

CodePudding user response:

Use split to split on whitespace; you can then get the first/last words from each string.

>>> text =  "I currently live in Chicago but  work in DC"
>>> keywords = 'live in'
>>> before, _, after = text.partition(keywords)
>>> before.split()[-1]
'currently'
>>> after.split()[0]
'Chicago'

CodePudding user response:

Just split the strings by the space character ( ) and get the first/last elements:

>>> before_keyword = before_keyword.split()[-1]
>>> after_keyword = after_keyword.split()[0]

>>> before_keyword
'currently'

>>> after_keyword
'Chicago'
  • Related