Python 修改正则表达式
我有几个字符串来匹配某些表达式,我想匹配并提取介词后面的两个单词以及prep本身。。他们也做得很好。但是我需要修改正则表达式,以便在介词后面出现单词“to”时,正则表达式将提取介词后面的3个单词(而不是默认的2个单词)Python 修改正则表达式,python,regex,string,function,conditional-statements,Python,Regex,String,Function,Conditional Statements,我有几个字符串来匹配某些表达式,我想匹配并提取介词后面的两个单词以及prep本身。。他们也做得很好。但是我需要修改正则表达式,以便在介词后面出现单词“to”时,正则表达式将提取介词后面的3个单词(而不是默认的2个单词) 下面是一个要详细说明的示例: str1 = " that place is near oberoi mall" str2 = " that place is next to oberoi mall" 预期结果:- res1=“near oberoi mall”#在prep之后提
下面是一个要详细说明的示例:
str1 = " that place is near oberoi mall"
str2 = " that place is next to oberoi mall"
预期结果:-res1=“near oberoi mall”
#在prep之后提取2个单词并与之一起使用(默认情况)res2=“oberoi mall旁边”
#提取prep,并在其后面加上3个单词(如果“to”在介词后面)
我做了什么
def landmark(str):
preps = ['near','off','next','across','opposite','behind','above','ahead']
words = "|".join(re.escape(line.rstrip()) for line in preps)
p1 = re.compile(r'(?:{})\s(\w+|\d+\w+)\s\w+'.format(words))
q =re.search(p1,str)
if q is None:
return ""
else:
return q.group()
我的prep在名为preps
这很好地返回了2个单词,所以我得到了
res1 = "near oberoi mall"
res2=“oberoi旁边”
#这将变得不完整
我试了什么?在这里:
*注意可选的(?:to)?我加了一个。有个小问题。。请提供帮助。这对您的示例有效:
>>> p1 = re.compile(r'(?:%s)\s((?:to\s)?(\w+|\d+\w+)\s\w+)' % words)
>>> dd = re.search(p1,str1)
>>> dd.group()
'near oberoi mall'
>>> cc = re.search(p1,str2)
>>> cc.group()
'next to oberoi mall'
这可能不会直接帮助您,但regex并不是用于此类操作的最佳工具。你看过了吗。据我所知,它支持类似的即时标记化。我的数据包含的地址不是英语的一部分。。那没用。。
>>> p1 = re.compile(r'(?:%s)\s((?:to\s)?(\w+|\d+\w+)\s\w+)' % words)
>>> dd = re.search(p1,str1)
>>> dd.group()
'near oberoi mall'
>>> cc = re.search(p1,str2)
>>> cc.group()
'next to oberoi mall'