繁体   English   中英

如何使用Python从Google Translate API访问JSON转换

[英]How to access JSON translation from Google Translate API with Python

我正在尝试学习塞尔维亚自动取款机,并让自己得到一个包含最常用单词的csv文件。
我现在想做的是让我的脚本通过API将每个单词放入Google Translate,并将此翻译保存到同一文件中。
由于我是Python和JSON的初学者,因此我对如何使用从API获取的JSON感到非常困惑。

我要如何翻译?

from sys import argv
from apiclient.discovery import build
import csv
import json

script, filename = argv
serbian_words = []

# Open a CSV file with the serbian words in one column (one per row)
with open(filename, 'rb') as csvfile:

    serbianreader = csv.reader(csvfile)

    for row in serbianreader:

        # Put all words in one single list
        serbian_words.extend(row)

        # send that list to google item by item to have it translated
        def main():

            service = build('translate', 'v2',
            developerKey='xxx')

            for word in serbian_words:

                translation = service.translations().list(
                    source='sr',
                    target='de',
                    q = word
                    ).execute()

                    print translation # Until here everything works totally fine.



if __name__ == '__main__':
  main()

终端为我打印的内容如下所示: {u'translations': [{u'translatedText': u'allein'}]}其中“ allein”是{u'translations': [{u'translatedText': u'allein'}]}单词的德语翻译。

我怎么去“ allein”? 我试图通过实现Python附带的json编码器和解码器来解决这个问题,但是我无法弄清楚。

我很乐意为此提供任何帮助,不胜感激。

您可以使用项目访问权限来获取最里面的字符串:

translation['translations'][0]['translatedText']

或者您可以遍历列出的所有翻译(这是一个列表):

for trans in translation['translations']:
    print trans['translatedText']

因为Google的翻译服务可以为给定的文本提供多种翻译。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM