在最常见的缩略语词典的基础上扩展英语缩略语
Expanding English contractions in, based on a dictionary of most common contractions
我正在尝试使用 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)
我试过在 "you're" 中添加“/”,但没用。
输出应该是扩展版本,但原始推文只是通过。
这里有一个线索:
>>> 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'
我正在尝试使用 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)
我试过在 "you're" 中添加“/”,但没用。
输出应该是扩展版本,但原始推文只是通过。
这里有一个线索:
>>> 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'