【问题标题】:Modifying a Regex Expression修改正则表达式
【发布时间】:2014-04-14 15:37:14
【问题描述】:

我有几个字符串来匹配我想要匹配的某些表达式,并在介词之后提取 2 个单词以及 preps 本身。他们也做得很好。但是我需要修改正则表达式,以防万一单词“to”出现在介词之后,正则表达式将提取介词后跟 3 个单词(而不是默认的 2 个单词..)
这是一个详细说明的例子:

str1 = " that place is near oberoi mall"
str2 = " that place is next to oberoi mall"

预期结果:-
res1 = "near oberoi mall" #extract prep 之后的 2 个单词(默认情况)
res2 = "next to oberoi mall" #extract 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()

我的准备在名为preps 的列表中 这在返回 2 个单词方面做得很好,所以我得到了

res1 = "near oberoi mall"

res2 = "next to oberoi"#这变得不完整

我尝试了什么?
这里:

p1 = re.compile(r'(?:{}(?:to)?)\s(\w+|\d+\w+)\s\w+'.format(words))  

*注意可选的 (?:to)?我为它添加了。有一些小问题..请帮忙。

【问题讨论】:

  • 这可能无法直接帮助您,但正则表达式并不是用于此类事情的最佳工具。你看过nltk。据我所知,它支持开箱即用的类似标记化。
  • 是的,我有。我的数据包含不属于英语的地址..这无济于事..

标签: python regex string function conditional-statements


【解决方案1】:

这适用于您的示例:

>>> 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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多