python - Finding words around a substring -
i have extract 2 words before , after substring match in large string. example:
sub = 'name' str = '''my name avi. name identifies are. important have name starting letter a.'''
now have find occurences of sub in str , return following:
(my name avi), (name identifies who), (have name starting with)
note if re full stop after string words before string returned shown in example above.
what have tried?
>>> import re >>> text = '''my name avi. name identifies are. important have name starting letter a.''' >>> m in re.finditer( 'name', text ): ... print( 'name found', m.start(), m.end() )
which gives me starting , ending position of matched substring. not able proceed further how find words around it.
import re sub = '(\w*)\w*(\w*)\w*(name)\w*(\w*)\w*(\w*)' str1 = '''my name avi. name identifies are. important have name starting letter a.''' in re.findall(sub, str1, re.i): print " ".join([x x in if x != ""])
output
my name avi name identifies have name starting
or,
sub = '\w*\w*\w*\w*name\w*\w*\w*\w*' in re.findall(sub, str1, re.i): i=i.strip(" .") print
Comments
Post a Comment