Python 如何在收缩标记化中反转正则表达式?
在Python 如何在收缩标记化中反转正则表达式?,python,regex,nlp,tokenize,substitution,Python,Regex,Nlp,Tokenize,Substitution,在nlp标记化中,收缩有时被拆分为: >>> import re >>> s = 'he cannot fly' >>> pattern, substitution = r"(?i)\b(can)(not)\b", r" \1 \2 " >>> re.sub(pattern, substitution, s) 'he can not fly' 为了扭转这种局面(即脱奥),我尝试了以下方法: >>>
nlp
标记化中,收缩有时被拆分为:
>>> import re
>>> s = 'he cannot fly'
>>> pattern, substitution = r"(?i)\b(can)(not)\b", r" \1 \2 "
>>> re.sub(pattern, substitution, s)
'he can not fly'
为了扭转这种局面(即脱奥),我尝试了以下方法:
>>> rev_pattern, rev_substitution = r"(?i)\b(can)\s(not)\b", r" \1\2 "
>>> re.sub(rev_pattern, rev_substitution, s)
'he cannot fly'
问题是r”(?i)\b(can)\s(not)\b“
和r”\1\2”
与原始模式替换的相反?有没有其他方法可以扭转这种局面
在本例中,我已将\s
手动编码到模式中。主要的问题是有一堆这些正则表达式是为标记化而手动编码的,我必须为它们手动添加\s
:
CONTRACTIONS2 = [re.compile(r"(?i)\b(can)(not)\b"),
re.compile(r"(?i)\b(d)('ye)\b"),
re.compile(r"(?i)\b(gim)(me)\b"),
re.compile(r"(?i)\b(gon)(na)\b"),
re.compile(r"(?i)\b(got)(ta)\b"),
re.compile(r"(?i)\b(lem)(me)\b"),
re.compile(r"(?i)\b(mor)('n)\b"),
re.compile(r"(?i)\b(wan)(na) ")]
CONTRACTIONS3 = [re.compile(r"(?i) ('t)(is)\b"),
re.compile(r"(?i) ('t)(was)\b")]
CONTRACTIONS4 = [re.compile(r"(?i)\b(whad)(dd)(ya)\b"),
re.compile(r"(?i)\b(wha)(t)(cha)\b")]
是否有一种方法可以自动遍历正则表达式列表,并在组之间添加\s
,而无需硬编码detokenzation正则表达式
我知道原始的标记化替换是->`r'\1\2',所以要撤销它,我必须将其更改回r'\1\2' 你可以在两者之间放置一条注释
(?#…)
。然后执行模式。替换
e、 g:
你可以在中间加一条注释(?#…)
。然后执行模式。替换
e、 g:
PATTERNS = [r"(?i)\b(can)(?#A)(not)\b",
r"(?i)\b(d)(?#A)('ye)\b",
r"(?i)\b(gim)(?#A)(me)\b",
r"(?i)\b(gon)(?#A)(na)\b"]
CONTRACTIONS = [re.compile(x) for x in PATTERNS]
REVERSORS = [re.compile(x.replace('(?#A)', '\s')) for x in PATTERNS]