@nhahtdh提出的答案是有效的,但我想比规范的示例少使用pythonic的示例,该示例使用比其regex操作少的代码不透明,并利用python的内置数据结构和匿名函数功能。
在这种情况下,翻译词典是有意义的。实际上,这就是Python Cookbook的工作方式,如本示例所示(从ActiveState
http://pre.activestate.com/recipes/81330-single-pass-multiple-
replace/复制)
import redef multiple_replace(dict, text): # Create a regular expression from the dictionary keys regex = re.compile("(%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)因此,根据您的情况,您可以做一个字典
trans = {"a": "aa", "b":"bb"},然后将其multiple_replace与要翻译的文本一起传递。基本上,该功能所要做的就是创建一个包含所有要翻译的正则表达式的巨大正则表达式,然后在找到该正则表达式时,将一个lambda函数传递
regex.sub给执行翻译字典查找。
您可以在读取文件时使用此功能,例如:
with open("notes.txt") as text: new_text = multiple_replace(replacements, text.read())with open("notes2.txt", "w") as result: result.write(new_text)实际上,在需要将一年中的几个月从捷克语翻译成英语以进行网络抓取任务的情况下,我实际上在生产中使用了这种精确方法。
正如@nhahtdh所指出的,这种方法的一个缺点是它不是无前缀的:作为其他字典键前缀的字典键将导致该方法中断。



