使用regex Python组合字符(如果存在于列表中)

2024-09-20 22:54:13 发布

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

如何检查文本中是否存在字符串,并替换它?我有这样的代码:

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 :)

正确的方法是什么?在


Tags: 字符串代码textrereadlikebutabout
3条回答

在这里,我传递了re.sub()一个匹配要收紧的图释的正则表达式和一个函数tighten_emoticon,它删除了匹配的regex对象的每个字符之间的空格。在

import re

def tighten_emoticon(matchobj):
    return matchobj.group(0).replace(" ", "")

original = 'I dont like politic : - ( but still read about it : - ) _ because its funny . : D and unpredictable : )'

tightened = re.sub(r'(: - \(|: - \)|: D|: \))', tighten_emoticon, original)

编辑

或者,可以使用emoticon列表动态生成正则表达式:

^{pr2}$

希望这个会好起来。在

import re

emoticon = [':)',':-)',':-(',':D']

def emoticonNormalize(text,loop=2):
    text = re.sub(r'\:\s*D', ':D', text)
    text = re.sub(r':\s*\-\s*\)', ':-)', text)
    text = re.sub(r'\:\s*\-\s*\(', ':-(', text)
    text = re.sub(r'\:\s*\)', ':)', 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}$
re.sub(r'(?<=\:)( )','',texta)
Out[72]: 'I dont like politic :- ( but still read about it :- ) _ because its funny . :D and unpredictable :)'

相关问题 更多 >

    热门问题