如何修改与Python中特定正则表达式匹配的文本?

Avi*_*jit 7 python regex nlp python-2.7

我需要在一个句子中标记负面背景.算法如下:

  1. 检测否定符(不是/从不/不是/不是/等)
  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
Run Code Online (Sandbox Code Playgroud)

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

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

I don't like you at all; I should not let you know my happiest secret.
Run Code Online (Sandbox Code Playgroud)

输出应该是:

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 .
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

Kas*_*mvd 4

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

([^.:;!?]*)
Run Code Online (Sandbox Code Playgroud)

然后你需要使用 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', '.')]
Run Code Online (Sandbox Code Playgroud)

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

>>> 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."
Run Code Online (Sandbox Code Playgroud)

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