我需要在句子中标记否定上下文。该算法如下:
现在,我定义了一个正则表达式来挑选所有此类事件:
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 .
我该怎么做呢?
首先,您最好将(?![.:;!?]).)*
否定的前瞻更改为否定的字符类。
([^.:;!?]*)
然后,您需要使用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()
在编辑后将其添加到句子末尾。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句