根据最常见的收缩字典扩大英语收缩

时间:2017-09-03 10:25:45

标签: python dictionary twitter preprocessor

我正在尝试使用Python替换收缩的单词,但面临错误。

import re
tweet = "I luv my <3 iphone & you're awsm apple. DisplayIsAwesome, sooo happppppy  http://www.apple.com"
contractions_dict = {"ain't": "am not",
                  "aren't": "are not",
                  "can't": "cannot",
                  "you're": "you are"}    

contractions_re = re.compile('(%s)' '|'.join(contractions_dict.keys()))

def expand_contractions(s, contractions_dict=contractions_dict):
    def replace(match):
        return contractions_dict[match.group(0)]

    return contractions_re.sub(replace, s)

expand_contractions(tweet)

我尝试在“你是”中添加“/”,但没有效果。

输出应该是扩展版本,但原来的推文只是通过了。

1 个答案:

答案 0 :(得分:1)

这里有一条线索:

>>> print('(%s)' '|'.join(contractions_dict.keys()))
you're(%s)|aren't(%s)|ain't(%s)|can't

由于%s在正则表达式中没有特殊含义,因此它只会匹配自身。但是输入中没有百分号,因此匹配失败。

我怀疑你在寻找像

这样的东西
>>> print('|'.join('(%s)' % k for k in contractions_dict.keys()))
(you're)|(aren't)|(ain't)|(can't)

或者

>>> print('(%s)' % '|'.join(contractions_dict.keys()))
(you're|aren't|ain't|can't)

但是,由于您使用的是match.group(0)(即整个匹配的字符串),因此捕获是无关紧要的,并且不需要在交替中对单词进行括号化。所以更简单的解决方案很好:

>>> contractions_re = re.compile('|'.join(contractions_dict.keys()))
>>> expand_contractions(tweet)
'I luv my <3 iphone & you are awsm apple. DisplayIsAwesome, sooo happppppy \xf0\x9f\x99\x82 http://www.apple.com'