【发布时间】:2018-12-17 18:32:40
【问题描述】:
我正在尝试使用字典替换 html 文件中的文本。
这可行,但不幸的是,如果文本被 html 标签包围或旁边有逗号,则与文本不匹配:
for key in dictionary:
print(key)
if key in answer_string:
pattern = re.compile(key, re.IGNORECASE)
answer_string = re.sub(r"[^ ]*"+pattern+r"[^ ]*", "<a href=\"" + dictionary.get(key) + "\">" + key + "</a>", answer_string)
这是我尝试过但不起作用的方法。我得到错误:TypeError: cannot concatenate 'str' and '_sre.SRE_Pattern' objects
for key in dictionary:
print(key)
if key in answer_string:
pattern = re.compile(key, re.IGNORECASE)
answer_string = re.sub(r"[^ ]*"+pattern+r"[^ ]*", "<a href=\"" + dictionary.get(key) + "\">" + key + "</a>", answer_string)
【问题讨论】:
标签: python regex dictionary replace