Python中正则表达式的否定标记

2024-09-30 08:32:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力使用Python中的regex实现否定标记,这是一个la Christopher Potts的sentiment analysis tutorial。你知道吗

从他的教程中,否定的定义是:

(?:
    ^(?:never|no|nothing|nowhere|noone|none|not|
        havent|hasnt|hadnt|cant|couldnt|shouldnt|
        wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint
    )$
)
|
n't

从句级标点的定义是:

^[.:;!?]$

其思想是捕捉否定和从句级标点之间的单词,然后修改它们以表明它们被否定,例如:

No one enjoys it.

应该变成这样:

No one_NEG enjoys_NEG it_NEG.

如有任何建议,将不胜感激。你知道吗


Tags: no标记定义itanalysisonetutorialla
1条回答
网友
1楼 · 发布于 2024-09-30 08:32:02

如果您有一个句子作为字符串,正如您所暗示的,那么您不能在regexp中使用“^”和“$”。改用\b。那么这就行了:

def add_negation_markers(m):
    return m.group(1) + re.sub(r'(?<=\w)\b', '_NEG', m.group(2))
re.sub('(' + neg_re + ')(.*)(?=' + punct_re + ')', add_negation_markers, text)

如果你有一个句子作为单词列表,就像$^标记所暗示的那样,那么。。。你知道吗

def negate(word):
    if re.search(punct_re, word):
        negate.should = False
    elif re.search(neg_re, word):
        negate.should = True
    elif negate.should:
        return word + '_NEG'
    return word
negate.should = False
map(negate, words)

相关问题 更多 >

    热门问题