Python 将记事本中参考文件中的[[Words]]替换为其他[[Words]]++;使用Javascript
我有一个如下所示的翻译文件:Python 将记事本中参考文件中的[[Words]]替换为其他[[Words]]++;使用Javascript,python,regex,replace,notepad++,regexp-replace,Python,Regex,Replace,Notepad++,Regexp Replace,我有一个如下所示的翻译文件: Apple=Apfel Apple pie=Apfelkuchen Banana=Banane Bananaisland=Bananen Insel Cherry=Kirsche Train=Zug …还有500多条这样的线路 现在我有一个文件需要处理文本。仅需替换文本的某些部分,例如: The [[Apple]] was next to the [[Banana]]. Meanwhile the [[Cherry]] was chilling by the [[
Apple=Apfel
Apple pie=Apfelkuchen
Banana=Banane
Bananaisland=Bananen Insel
Cherry=Kirsche
Train=Zug
…还有500多条这样的线路
现在我有一个文件需要处理文本。仅需替换文本的某些部分,例如:
The [[Apple]] was next to the [[Banana]]. Meanwhile the [[Cherry]] was chilling by the [[Train]].
The [[Apple pie]] tastes great on the [[Bananaisland]].
结果需要得到证实
The [[Apfel]] was next to the [[Banane]]. Meanwhile the [[Kirsche]] was chilling by the [[Zug]].
The [[Apfelkuchen]] tastes great on the [[Bananen Insel]].
事件太多,无法手动复制/粘贴。如前所述,从另一个文件中搜索[[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])
然而,这将取代太多,或不一致。例如,[[Apple]]被[[Apfel]]正确替换,但是[[File:Apple.png]]被[[File:Apfel.png]]错误替换,[[Apple pie]]被[[Apfel pie]]替换,所以我连续几个小时尝试调整正则表达式,但都没有效果。是否有人有任何信息-请简单地说-我如何解决这个问题/实现我的目标?首先,阅读文件中的翻译:
translations={}
将open('file/with/translations.txt','r',encoding='utf-8')作为f:
对于f中的行:
items=line.strip().split('=',1)
翻译[项目[0]]=项目[1]
我假设这些短语/单词在文件中是唯一的。
然后,您需要匹配[[
和]
之间的所有子字符串,捕获中间的文本(使用类似于\[\[(.*?)]]
的正则表达式,请参见),检查翻译字典中是否有具有组1值的键,如果有这样的键,则替换为[
+字典值+]]
,如果没有这样的翻译,则返回整个匹配:
text=“”[[苹果]]就在[[香蕉]]的旁边。与此同时[[樱桃]]在[[火车]]旁冷却。
[[苹果派]]在[[巴纳纳岛]]上味道很好
进口稀土
translated_text=re.sub(r“\[\[(.*?)]]”,lambda x:f'[{translates[x.group(1)]}]',如果翻译中的x.group(1)是其他x.group(),text)
输出:
>>翻译文本
“[[Apfel]]就在[[Banane]]的旁边。与此同时,[[Kirsche]]被[[Zug]]冷了下来\Nn[[Apfelkuchen]]在[[Bananen Insel]]上味道很好
这有点棘手,因为[在正则表达式中是一个元字符
我相信有一种更有效的方法可以做到这一点,但这是可行的:
replaces=“”苹果=Apfel
苹果派
香蕉=香蕉烷
巴纳纳岛=巴纳南插图
樱桃=Kirsche
火车=Zug
text=”“”
[[苹果]]在[[香蕉]]的旁边。与此同时[[樱桃]]在[[火车]]旁冷却。
[[苹果派]]在[[巴纳纳岛]]上味道很好。
"""
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
进口稀土
对于replaces.split('\n')中的replace:
英语,德语=replace.split('='))
text=re.sub(rf'\[\[{english}\]\]',f'[{german}]]',text)
打印(文本)
产出:
The [[Apfel]] was next to the [[Banane]]. Meanwhile the [[Kirsche]] was chilling by the [[Zug]].
The [[Apfelkuchen]] tastes great on the [[Bananen Insel]].
另外,还发布了两次使用答案中的代码部分。请。每个社区都应该有一个诚实的回答机会,而不会浪费任何人的时间。