我对Python还是相当陌生的,我的脚本有一些问题
我的文件中有如下句子:
Comment "This is my line with [special words <mots spéciaux>] that I will need to swap"
Translation "Voici ma phrase avec des [mots spéciaux incorrects] que je dois modifier"
我需要从我的翻译行中提取[mots spéciaux incorrects],并将其替换为我评论行的一部分
我创建了一个以注释翻译为关键值的词典。我浏览字典并使用正则表达式捕获[special words]
段。
如果我每行只有一个单词需要修改,我的脚本就可以正常工作。但是,每当我有多个片段时,只有第一个片段被更改
for i in lines_dict:
brackets_context = re.findall(r'\[[\w|\s]* <[\w|\s]*>\]', i)
if brackets_context:
print(i, lines_dict[i])
target_brackets = re.search(r'\[[\w|\s]*', i).group()
source_brackets = re.search(r'<([\w|\s]*)>', i).group()
brackets_translation = re.search(r'\[[\w|\s]*\]', lines_dict[i]).group()
new_translation = lines_dict[i].replace(brackets_translation, target_brackets)
print("New translation %s\n" % new_translation)
lines_dict[i] = new_translation
我想有很多简单的方法来做我需要的事情,但我完全被卡住了。我尝试过几种方法,并查看了其他回答的问题,但我没有找到适合我的脚本的方法,我似乎无法完成整个过程并替换所有内容,我有点绝望……有人知道我应该如何继续吗
因此,我当前的输入是一个包含许多块的文件,例如:
comment "Vous avez la liste des [growers <exploitants>] liés aux [blocks <parcelles>] saisies dans l'[work order <ordre de travail>]."
translation "You have the list of [operators] related to the [plots] entered in the [work order]."
我需要把它作为输出:
comment "Vous avez la liste des [growers <exploitants>] liés aux [blocks <parcelles>] saisies dans l'[work order <ordre de travail>]."
translation "You have the list of growers related to the blocks entered in the work order."
现在让我们忽略这句话,只关注字符串:
基本上,您试图做的是用
comment
的相应部分替换translation
的部分。因此re.sub
将是在translation
上使用的一个好工具。它可以使用替换函数,我们可以将其连接到搜索comment
的函数因此,首先让我们使用
re.finditer
获取替换字符串:在这里,我使用
?
来执行non-greedy matches,并且.*
来保持简单(如果需要,您可以替换它)。还要注意,我把重要的一点放在第一组下一步是更换:
让我们分解替换函数,
lambda _: next(targets).group(1)
:_
-re.sub
传入匹配对象,但我们不需要它,因此下划线表示我们忽略了参数targets
输出:
相关问题 更多 >
编程相关推荐