符号之间的单词替换

符号之间的单词替换

我有一个如下所示的翻译文件:

Apple=Apfel
Banana=Banane
Cherry=Kirsche
Train=Zug

...还有 500 多行类似的内容

现在我有一个需要处理文本的文件。只需要替换文本的某些部分,例如:

The [[Apple]] was next to the [[Banana]]. Meanwhile the [[Cherry]] was chilling by the [[Train]].

结果需要

The [[Apfel]] was next to the [[Banane]]. Meanwhile the [[Kirsche]] was chilling by the [[Zug]].

手动复制/粘贴的事件太多了。有什么简单的方法可以搜索 [[XXX]] 并从另一个文件中替换?我测试过

import re
separators = "=", "\n"

def custom_split(sepr_list, str_to_split):
    # create regular expression dynamically
    regular_exp = '|'.join(map(re.escape, sepr_list))
    return re.split(regular_exp, str_to_split)

with open('D:/_working/paired-search-replace.txt') as f:
    for l in f:
        s = custom_split(separators, l)
        editor.replace(s[0], s[1])

但它也会将不需要的东西(例如,将 [[File:Apple.png]] 替换为 [[File:Apfel.png]]) ,而这是不应该发生的。

相关内容