如何检查文本中是否存在字符串,并替换它?我有这样的代码:
import re
emoticon = [':)',':-)',':-(',':D']
def emoticonNormalize(text,loop=2):
text = re.sub(r'\s(\S)\s(\S)\s(\S)\s', r' \1\2\3 ', text)
text = re.sub(r'\s(\S)\s(\S)\s', r' \1\2 ', text)
text = re.sub(r'\s(\S)\s(\S)', r' \1\2', text)
print(text)
texta = 'I dont like politic : - ( but still read about it : - ) _ because its funny . : D and unpredictable : )'
print(texta)
texted = emoticonNormalize(texta,1)
代码结果:
^{pr2}$因此,texta
中的字符串包含实际上是一个图释的字符,但它仍然由空格分隔。我正在尝试使用regex组合看起来像表情符号。在
我想先找到可疑的表情符号。然后检查它是否在emoticon
列表中,如果它在列表中,则用combineone替换旧模式(仍有空格)。在
我很困惑如何使用re.sub
,预期结果是I dont like politic :-( but still read about it :-) _ because its funny . :D and unpredictable :)
正确的方法是什么?在
在这里,我传递了
re.sub()
一个匹配要收紧的图释的正则表达式和一个函数tighten_emoticon
,它删除了匹配的regex对象的每个字符之间的空格。在编辑
或者,可以使用
^{pr2}$emoticon
列表动态生成正则表达式:希望这个会好起来。在
输出:
^{pr2}$相关问题 更多 >
编程相关推荐