Last active
May 19, 2018 18:13
-
-
Save prasadsunny1/e189c6eb37fc6941536951d75cfb5890 to your computer and use it in GitHub Desktop.
This python script takes an xml file and translaes all the values tagged with <value> in your target language(set target="LANG_CODE" in the script)
This file contains hidden or 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
# -*- coding: utf-8 -*- | |
from google.cloud import translate | |
import six | |
import xml.dom.minidom as minidom | |
def translate_text(target, text): | |
"""Translates text into the target language. | |
Target must be an ISO 639-1 language code. | |
See https://g.co/cloud/translate/v2/translate-reference#supported_languages | |
""" | |
translate_client = translate.Client.from_service_account_json( | |
'YOUR_GCP_KEY_FILE.json') | |
if isinstance(text, six.binary_type): | |
text = text.decode('utf-8') | |
# Text can also be a sequence of strings, in which case this method | |
# will return a sequence of results for each text. | |
result = translate_client.translate( | |
text, target_language=target) | |
print(u'Text: {}'.format(result['input'])) | |
print(u'Translation: {}'.format(result['translatedText'])) | |
print(u'Detected source language: {}'.format( | |
result['detectedSourceLanguage'])) | |
return result['translatedText'] | |
def main(): | |
target="hi" | |
# use the parse() function to load and parse an XML file | |
doc = minidom.parse("language_pack.xml"); | |
# print out the document node and the name of the first child tag | |
print (doc.nodeName) | |
print (doc.firstChild.tagName) | |
doc.firstChild.setAttribute("Name", target) | |
translate_text("fr","hello world") | |
Value = doc.getElementsByTagName("Value") | |
print ("%d Value:" % Value.length) | |
for val in Value: | |
print (val.firstChild.data) | |
result=translate_text(target,val.firstChild.data) | |
print('translation:',result) | |
val.firstChild.data=result | |
print (val.firstChild.data) | |
fileName='{}-{}{}'.format('language_pack',target,'.xml') | |
file_handle = open(fileName,"wb") | |
a=doc.toxml("UTF-8") | |
file_handle.write(a) | |
file_handle.close() | |
if __name__ == "__main__": | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment