Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding the next and previous word after keyword

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading