我想将字符串"<75%“替换为"NONE”。我写了这个函数,但它不匹配:(
replacements = {'toot': 'titi-',
'<75%': 'NONE'}
def replace(match):
return replacements[match.group(0)]
def clean75Case(text_page):
return re.sub('|'.join(r'\b%s\b' % re.escape(s) for s in replacements),
replace, text_page)
if __name__ == '__main__':
print(clean75Case("toot iiii <75%"))
发布于 2019-06-06 05:41:23
正如评论中提到的,问题是\b
只匹配单词和非单词字符之间的边界。来自the docs
\b
匹配空字符串,但仅在单词的开头或结尾。单词被定义为单词字符的序列。请注意,在形式上,\b被定义为\w和\W字符之间的边界(反之亦然),或者\w和字符串的开头/结尾之间的边界
在您给出的字符串中,空格字符()和小于字符(<
)都是非单词字符。因此,\b
与它们之间的空格不匹配。
要解决此问题的另一种方法,请考虑使用split()
将字符串拆分成单词,并将每个单词与替换模式进行比较,如下所示:
replacements = {'toot': 'titi-',
'<75%': 'NONE'}
def clean75Case(text_page):
words = text_page.split()
return ' '.join(replacements.get(w, w) for w in words)
if __name__ == '__main__':
print(clean75Case("toot iiii <75%"))
https://stackoverflow.com/questions/56468289
复制相似问题