Neeraj Kumar
Neeraj Kumar

Reputation: 3941

Regex for replace msgstr in PO file data using python

I have list content = ['x', 'y', 'z']

.po file content:

msgid 'abc'
msgstr ''

msgid 'def'
msgstr ''

msgid 'ghi'
msgstr ''

I need output like below:

msgid 'abc'
msgstr 'x'

msgid 'def'
msgstr 'y'

msgid 'ghi'
msgstr 'z'

Edit:

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

So filedata has all content of PO file

Upvotes: -2

Views: 266

Answers (2)

salparadise
salparadise

Reputation: 5815

Might need to explain more about the relationship of your data. You want to write the entries based on order or is there some relationship between 'abc' and 'x' for example. Anyways, here is if you want ordering (not regex):

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'

EDIT, change file inplace (make sure you save a copy of the file)

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)

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92894

The solution using built-in iter() function and re.sub() function:

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)

The output:

msgid 'abc'
msgstr 'x'

msgid 'def'
msgstr 'y'

msgid 'ghi'
msgstr 'z'

Upvotes: 1

Related Questions