I have the sentence : Take 1 tablet in the morning and at noon for **1** week
I try to find the position of the 1 element corresponding to the 1 for 1 week
But if i use re.search for the '1' element in my sentence i've got the 1 position from the 1 element corresponding to 1 tablet
Thanks to NLP I can extract the element for 1 week
. So i would like to find the 1 element in the substring for 1 week
in the sentence.
CodePudding user response:
You can find the span of for 1 week
and the span of 1
within for 1 week
(this is quite trivial in this example but would be more interesting with a more complex regex):
s = 'Take 1 tablet in the morning and at noon for 1 week'
import re
m = re.search('for 1 week', s)
start, stop = m.span()
m2 = re.search('1', m.group())
start2, stop2 = m2.span()
start start2
output:
>>> start start2
45
>>> s[45]
'1'
slightly more complex example:
m = re.search('(for|during) \d (week|day|month)', s)
start, stop = m.span()
m2 = re.search('\d ', m.group())
start2, stop2 = m2.span()
print(f'position {start start2}: {s[start start2]}')
output: position 45: 1