python正则替换多个,在python中如何使⽤正则表达式进⾏多
个替换?
@nhahtdh提出的答案是有效的,但是我⽐那些使⽤⽐正则表达式操作更不透明的代码,并利⽤python的内置数据结构和匿名函数功能的规范例⼦来说,它的争论⽐较少。
import re
def multiple_replace(dict, text):
# Create a regular expression from the dictionary keys
regex = repile("(%s)" % "|".join(map(re.escape, dict.keys())))
# For each match, look-up corresponding value in dictionary
return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
if __name__ == "__main__":
text = "Larry Wall is the creator of Perl"
dict = {
"Larry Wall" : "Guido van Rossum",
"creator" : "Benevolent Dictator for Life",
"Perl" : "Python",
}
print multiple_replace(dict, text)
所以在你的情况下,你可以使⼀个dict trans = {“a”:“aa”,“b”:“bb”},然后将其传递到multiple_replace以及要翻译的⽂本。基本上所有这些功能正在创建⼀个包含所有正则表达式进⾏翻译的巨型正则表达式,然后当到⼀个正则表达式时,将lambda函数传递给regex.sub来执⾏翻译字典查。
您可以在从⽂件中读取时使⽤此功能,例如:
python正则表达式不包含
with open("") as text:
new_text = multiple_replace(replacements, ad())
with open("", "w") as result:
result.write(new_text)
我实际上在⽣产中使⽤了这种确切的⽅法,在这种情况下,我需要将捷克语中的⼏个⽉翻译成英⽂,以进⾏⽹络抓取任务。
正如@nhahtdh所指出的那样,这种⽅法的⼀个缺点是它不是前缀:字典键是其他字典键的前缀将导致该⽅法中断。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。