-2

我有清单content = ['x', 'y', 'z']

.po 文件内容:

msgid 'abc'
msgstr ''

msgid 'def'
msgstr ''

msgid 'ghi'
msgstr ''

我需要如下输出:

msgid 'abc'
msgstr 'x'

msgid 'def'
msgstr 'y'

msgid 'ghi'
msgstr 'z'

编辑:

with io.open('file.po, 'r', encoding='utf-8') as pofile:
    filedata = pofile.read()

所以filedata有PO文件的所有内容

4

2 回答 2

1

使用内置iter()函数和re.sub()函数的解决方案:

import re

content = ['x', 'y', 'z']
po_data = '''
msgid 'abc'
msgstr ''

msgid 'def'
msgstr ''

msgid 'ghi'
msgstr ''
'''

content_it = iter(content)    # constructing iterator object from iterable
result = re.sub(r'(msgstr )\'\'', lambda m: "%s'%s'" % (m.group(1), next(content_it)), po_data)

print(result)

输出:

msgid 'abc'
msgstr 'x'

msgid 'def'
msgstr 'y'

msgid 'ghi'
msgstr 'z'
于 2017-09-17T07:53:26.683 回答
0

可能需要更多地解释您的数据关系。您想根据顺序编写条目,或者例如“abc”和“x”之间是否存在某种关系。无论如何,如果你想订购(不是正则表达式),这里是:

In [30]: cat /tmp/somefile
msgid 'abc'
msgstr ''

msgid 'def'
msgstr ''

msgid 'ghi'
msgstr ''

In [31]: content = ['x', 'y', 'z']

In [32]: with open('/tmp/somefile', 'r') as fh, open('/tmp/somenewfile', 'w') as fw:
    ...:     for line in fh:
    ...:         if 'msgstr' in line:
    ...:             line = "msgstr '{}'\n".format(content.pop(0))
    ...:         fw.write(line)
    ...:
    ...:

In [33]: cat /tmp/somenewfile
msgid 'abc'
msgstr 'x'

msgid 'def'
msgstr 'y'

msgid 'ghi'
msgstr 'z'

编辑,就地更改文件(确保保存文件的副本)

with open('/tmp/somefile', 'r+') as fw:
    lines = fw.readlines()
    fw.seek(0)
    fw.truncate()
    for line in lines:
        if 'msgstr' in line:
            line = "msgstr '{}'\n".format(content.pop(0))
        fw.write(line)
于 2017-09-17T08:05:32.067 回答