用另一个文件的值编辑一个文件(用python修复.xliff文件)

2024-09-28 17:05:53 发布

您现在位置:Python中文网/ 问答频道 /正文

问题:
1我们项目的基本语言是En,我们需要更改一些值(因此我们的开发人员导出En.xliff,其中和语言都是En)

2xliff导入工具只期望被更改-如果被更改,它抛出导入错误并忽略这些单位

我使用的3个TMS(lokalise.com)正在同时更改和,因此我无法输入文件 返回项目

所以现在我尝试用Python来解决这个问题(我不是开发人员,但喜欢解决问题)
我的决定是在普通文件(来自xcode)和坏文件(来自TMS)中查找-如果键匹配,我需要脚本将下一行更改为原始行

以下是代码:

import re
key1 = re.compile(r'(?<=<trans-unit id=\").*(?=\" xml:space=\"preserve\">\n)')
key2 = re.compile(r'(?<=<trans-unit id=\").*(?=\">\n)')
src = re.compile(r'(?<=<source>).*(?=</source>\n)')
trg = re.compile(r'(?<=<target>).*(?=</target>\n)')
pattern = key1
inf = open(r'...\test\en.xliff', 'r')
outf = open('out.xliff', 'w')
tofix = open(r'...\test\changed\en.xliff', 'r')
in_buf = inf.readlines()
tofix_buf = tofix.readlines()
tofix.close()
inf.close()

for ind in range(len(in_buf)):
        if re.findall(key1, in_buf[ind]):
            outf.write(in_buf[ind])
            for ind2 in range(len(tofix_buf)):
                if re.findall(key2,tofix_buf[ind2]) == re.findall(key1, in_buf[ind]):
                    print('foo')
                    outf.write(in_buf[ind+1])
                    outf.write(tofix_buf[ind2+2])
        elif re.findall(src,in_buf[ind]) or re.findall(trg,in_buf[ind]):
            continue
        else:
            outf.write(in_buf[ind])

outf.close()
print('Done')

.xliff文件格式示例:

      <trans-unit id="Any questions about your device or application?" xml:space="preserve">
        <source>Any questions about your device or application?</source>
        <target>Any questions about your device or application?</target>
        <note>+ Dashboard. Support block title</note>
      </trans-unit>

至于现在,我的代码似乎在普通情况下工作。但问题是,如果原始dev的.xliff文件包含任何重复的单元id,那么它将以不同的顺序粘贴两个重复的源和目标

原始示例(副本):

1)
      <trans-unit id="CFBundleName" xml:space="preserve">
        <source>1</source>
        <target>1</target>                 
        <note>Bundle name</note>
2)
      <trans-unit id="CFBundleName" xml:space="preserve">
        <source>2</source>  
        <target>2</target>
        <note>Bundle name</note>

示例(具有断开值的相同键):

1)
      <trans-unit id="CFBundleName" xml:space="preserve">
        <source>1</source>
        <target>1</target>
        <source>1</source>
        <target>2</target>
        <note>Bundle name</note>
2)
      <trans-unit id="CFBundleName" xml:space="preserve">
        <source>2</source>
        <target>1</target>
        <source>2</source>
        <target>2</target>
        <note>Bundle name</note>

因此,代码以奇怪的顺序混合了源/目标值,我无法捕获并确定错误。
请,有经验的程序员,我如何修复它?
如果可能的话-不需要对代码做太多更改,因为我成功地理解了它,这真是一个奇迹(=)


Tags: inreidsourcetargettransunitspace