Created
July 26, 2017 19:26
-
-
Save not7cd/916d24c9700ea6621516edbc25410424 to your computer and use it in GitHub Desktop.
Translate elements in XML and add proper "lang" attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from lxml import etree | |
import mtranslate | |
import copy | |
def copy_element(element): | |
"""Copies element usin deepcopy, returns it""" | |
result = copy.deepcopy(element) | |
return result | |
def duplicate_element(element): | |
"""Creates copy of given element within parent, | |
changes its """ | |
parent = element.getparent() | |
result = copy_element(element) | |
parent.append(result) | |
# if result.getparent() != parent: | |
return result | |
def open_file(path): | |
parser = etree.XMLParser(strip_cdata=False) | |
with open(path, "rb") as source: | |
return etree.parse(source, parser=parser) | |
def write_file(tree, path): | |
et = etree.ElementTree(tree) | |
et.write(path, pretty_print=True, encoding="utf-8") | |
def translate_elements(elements): | |
for element in elements: | |
parent = element.getparent() | |
translated_element = duplicate_element(element) | |
try: | |
translated_text = mtranslate.translate(element.text, "pl") | |
translated_element.text = etree.CDATA(translated_text) | |
except Exception as e: | |
print(e) | |
translated_element.attrib['lang'] = 'pl_PL' | |
print(translated_element.getparent(), etree.tostring(translated_element)) | |
print(element.getparent(), etree.tostring(element)) | |
def position_elements(elements): | |
for element in elements: | |
parent = element.getparent() | |
lower_neighbour = parent.find('.//%s[@lang="pt_BR"]' % element.tag) | |
try: | |
insert_index = parent.index(lower_neighbour) | |
parent.insert(insert_index, element) | |
except Exception as e: | |
print(e) | |
def main(): | |
tree = open_file('cpt_org.xml') | |
root = tree.getroot() | |
translate_elements([child for child in root.findall('.//*[@lang="en_US"]')]) | |
position_elements([child for child in root.findall('.//*[@lang="pl_PL"]')]) | |
write_file(root, 'result.xml') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example
// TODO