我想在数组中创建查找字符串的函数,然后从字典中替换corres [ponding元素]。到目前为止,我已经尝试过这个,但我无法弄清楚像
这样的事情\1
但是没有用DSDS
def myfunc(h):
myarray = {
"#":"\\#",
"$":"\\$",
"%":"\\%",
"&":"\\&",
"~":"\\~{}",
"_":"\\_",
"^":"\\^{}",
"\\":"\\textbackslash{}",
"{":"\\{",
"}":"\\}"
}
pattern = "[#\$\%\&\~\_\^\\\\\{\}]"
pattern_obj = re.compile(pattern, re.MULTILINE)
new = re.sub(pattern_obj,myarray[\1],h)
return new
答案 0 :(得分:3)
您正在寻找re.sub回调:
def myfunc(h):
rules = {
"#":r"\#",
"$":r"\$",
"%":r"\%",
"&":r"\&",
"~":r"\~{}",
"_":r"\_",
"^":r"\^{}",
"\\":r"\textbackslash{}",
"{":r"\{",
"}":r"\}"
}
pattern = '[%s]' % re.escape(''.join(rules.keys()))
new = re.sub(pattern, lambda m: rules[m.group()], h)
return new
这样你可以避免1)循环,2)替换已处理的内容。
答案 1 :(得分:1)
您可以尝试在遍历myarray.items()的循环中使用re.sub。但是,您必须首先执行反斜杠,否则可能会错误地替换错误。您还需要确保首先发生“{”和“}”,这样您就不会混淆匹配。由于字典是无序的,我建议您使用元组列表:
def myfunc(h):
myarray = [
("\\","\\textbackslash")
("{","\\{"),
("}","\\}"),
("#","\\#"),
("$","\\$"),
("%","\\%"),
("&","\\&"),
("~","\\~{}"),
("_","\\_"),
("^","\\^{}")]
for (val, replacement) in myarray:
h = re.sub(val, replacement, h)
h = re.sub("\\textbackslash", "\\textbackslash{}", h)
return h
答案 2 :(得分:1)
r""
)以提高代码的可读性。str.replace
函数而不是re.sub
。def myfunc(h):
myarray = [
("\\", r"\textbackslash"),
("{", r"\{"),
("}", r"\}"),
("#", r"\#"),
("$", r"\$"),
("%", r"\%"),
("&", r"\&"),
("~", r"\~{}"),
("_", r"\_"),
("^", r"\^{}")]
for (val, replacement) in myarray:
h = h.replace(val, replacement)
h = h.replace(r"\textbackslash", r"\textbackslash{}", h)
return h
该代码是@ tigger答案的修改。
答案 3 :(得分:0)
要转义元字符,请使用原始字符串和反斜杠
r"regexp with a \* in it"