Search code examples
pythonregexpo-file

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


Solution

  • 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'