Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python从Google Translate API访问JSON翻译_Python_Json_Google Api_Google Translate - Fatal编程技术网

如何使用Python从Google Translate API访问JSON翻译

如何使用Python从Google Translate API访问JSON翻译,python,json,google-api,google-translate,Python,Json,Google Api,Google Translate,我正在努力学习塞尔维亚atm,并为自己准备了一个包含最常用单词的csv文件。 我现在想做的是让我的脚本通过API将每个单词放入Google Translate,并将此翻译保存到同一个文件中。 由于我完全是Python和JSON的初学者,我对如何使用从API获得的JSON感到非常困惑 我怎么去翻译 from sys import argv from apiclient.discovery import build import csv import json script, filename =

我正在努力学习塞尔维亚atm,并为自己准备了一个包含最常用单词的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”是塞尔维亚语单词的德语翻译

我怎样才能到达“allein”?我试图通过实现Python附带的json编码器和解码器来解决这个问题,但我无法解决


我希望能在这方面得到任何帮助,并将不胜感激。

您可以使用item access访问最里面的字符串:

translation['translations'][0]['translatedText']
或者您可以循环查看列出的所有翻译(这是一个列表):

因为谷歌的翻译服务可以为给定的文本提供多个翻译

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