【问题标题】:How to modify text that matches a particular regular expression in Python?如何修改与 Python 中特定正则表达式匹配的文本?
【发布时间】:2016-04-05 21:43:23
【问题描述】:

我需要在句子中标记否定上下文。算法如下:

  1. 检测否定符(not/never/ain't/don't/ 等)
  2. 检测子句结尾标点符号 (.;:!?)
  3. 在这之间的所有单词中添加 _NEG。

现在,我已经定义了一个正则表达式来挑选所有此类事件:

def replacenegation(text):
    match=re.search(r"((\b(never|no|nothing|nowhere|noone|none|not|havent|hasnt|hadnt|cant|couldnt|shouldnt|wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint)\b)|\b\w+n't\b)((?![.:;!?]).)*[.:;!?\b]", text)
    if match:
        s=match.group()
        print s
        news=""
        wlist=re.split(r"[.:;!? ]" , s)
        wlist=wlist[1:]
        print wlist
        for w in wlist:
            if w:
                news=news+" "+w+"_NEG"
        print news

我可以检测并替换匹配的组。但是,我不知道如何在此操作后重新创建完整的句子。同样对于多个匹配,match.groups() 给我错误的输出。

例如,如果我的输入句子是:

I don't like you at all; I should not let you know my happiest secret.

输出应该是:

I don't like_NEG you_NEG at_NEG all_NEG ; I should not let_NEG you_NEG know_NEG my_NEG happiest_NEG secret_NEG .

我该怎么做?

【问题讨论】:

    标签: python regex python-2.7 nlp


    【解决方案1】:

    首先,您最好将否定前瞻 (?![.:;!?]).)* 更改为否定字符类。

    ([^.:;!?]*)
    

    然后您需要使用 none 捕获组并删除多余的否定词,因为您已将其包围在 3 个捕获组中,它将返回您的否定词的 3 个匹配项,例如 not。然后您可以使用re.findall() 查找所有匹配项:

    >>> regex =re.compile(r"((?:never|no|nothing|nowhere|noone|none|not|havent|hasnt|hadnt|cant|couldnt|shouldnt|wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint)\b|\b\w+n't\b)([^.:;!?]*)([.:;!?\b])")
    >>> 
    >>> regex.findall(s)
    [("don't", ' like you at all', ';'), ('not', ' let you know my happiest secret', '.')]
    

    或者要替换单词,您可以使用 re.sub 与 lambda 函数作为替换器:

    >>> regex.sub(lambda x:x.group(1)+' '+' '.join([i+'_NEG' for i in x.group(2).split()])+x.group(3) ,s)
    "I don't like_NEG you_NEG at_NEG all_NEG; I should not let_NEG you_NEG know_NEG my_NEG happiest_NEG secret_NEG."
    

    请注意,要捕获标点符号,您还需要将其放入捕获组。然后您可以在编辑后将其添加到re.sub()的句子末尾。

    【讨论】:

    • 这很完美!至于标点符号,我还可以在文本上运行一个简单的标记器,因为无论如何我都必须区分它们和表情符号。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多