gpt4 book ai didi

python - 模式匹配和编译

转载 作者:行者123 更新时间:2023-12-01 05:26:23 25 4
gpt4 key购买 nike

我是模式匹配的新手,并且有这样的功能:

def replaceSynonymns(title, words):
pattern = re.compile(r'\b(' + '|'.join(words) + ')\b')
title = re.sub(pattern, words[0], title)
return title

单词的一个例子是 ['web', 'internet', 'online', 'digital'],因此,如果我们在标题中输入 'I'm on the internet',我们应该得到 'I'我在网络上'

但不幸的是它不起作用 - 因为我认为将列表合并到编译模式部分是不正确的 - 有什么提示吗?

最佳答案

最后一个字符串也使用原始字符串:

>>> r'\b(' + '|'.join(words) + r')\b' 
'\\b(web|internet|online|digital)\\b'

否则你最终会得到:

>>> r'\b(' + '|'.join(words) + ')\b'
'\\b(web|internet|online|digital)\x08'
^
not escaped

或者更好地使用string formatting :

>>> r'\b({})\b'.format('|'.join(words))
'\\b(web|internet|online|digital)\\b'

作为旁注,您可以在编译模式本身上使用 .sub:

title = pattern.sub(words[0], title)

关于python - 模式匹配和编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21270006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com