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? ie currently
for before_keyword and Chicago
in after_keyword.
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'
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'
First, we partition the text
variable.
Second, we get the last index of text.partition(keywords)[0]
by using .split()[-1]
. This will be assigned to the before
variable.
Third, we get the first index of text.partition(keywords)[2]
using .split()[0]
and this will be assigned to the after
variable.
>>> text = "I currently live in Chicago but work in DC"
>>> keywords = 'live in'
>>> before = text.partition(keywords)[0].split()[-1]
>>> after = text.partition(keywords)[2].split()[0]
>>> before
'currently'
>>> after
'Chicago'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.