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.
>Solution :
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'