繁体   English   中英

Python 正则表达式替换模式列表

[英]Python regex replace list of pattern

我有一个模式列表:

patterns = ["how", "do you do", "are you doing", "goes it"]

字符串中出现的任何列表项都应替换为"how are you"

例如:

字符串“你好吗?” 应该换成“你好吗?”

我用什么:

s = input()  
for pattern in patterns:
       s = re.sub(rf"(\b{pattern}\b)", "how are you", s)

问题是我收到"how are you how are you"

最简单的解决方案是将模式列表更改为:

patterns = ["how do you do", "how are you doing", "how goes it"]

但我需要将“如何”保留在列表中并将其与其他项目分开。

问题与re.sub内部和外部的s有关,这会覆盖input()使用另一个 varialbe,例如m

s = input()  
for pattern in patterns:
    m = re.sub(rf"(\b{pattern}\b)", "how are you", s)

请您尝试以下操作:

import re

patterns = ["how", "do you do", "are you doing", "goes it"]
first = patterns.pop(0)                 # pop the 1st element
pattern = rf"\b{first}\s+(?:" + "|".join(patterns) + r")\b"
# pattern equals to r"\bhow\s+(?:do you do|are you doing|goes it)\b"
s = input()
s = re.sub(pattern, "how are you", s)
print(s)

如果您更喜欢使用循环,可以使用以下替代方法:

import re

patterns = ["how", "do you do", "are you doing", "goes it"]
first = patterns.pop(0)                 # pop the 1st element
s = input()
for pattern in patterns:
    s = re.sub(rf"\b{first}\s+{pattern}\b", "how are you", s)
print(s)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM