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

时间:2016-01-01 08:07:28

标签: python regex python-2.7 nlp

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

  1. 检测否定者(不是/从不/不是/不是/等)
  2. 检测结束标点符号的句子(。;:!?)
  3. 将_NEG添加到此之间的所有字词。
  4. 现在,我已经定义了一个正则表达式来挑选所有这些出现的情况:

    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 .
    

    我该怎么做?

1 个答案:

答案 0 :(得分:4)

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

([^.:;!?]*)

然后你需要使用没有捕获组并删除额外的消极组,因为你已经被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()中的句子末尾添加它。