2

我正在尝试学习塞尔维亚语 atm,并为自己获取了一个包含最常用单词的 csv 文件。
我现在想做的是让我的脚本通过 API 将每个单词放入谷歌翻译,并将翻译保存到同一个文件中。
由于我完全是 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编码器和解码器来解决这个问题,但我无法弄清楚。

I'd love any help on this and would be very grateful.

4

1 回答 1

1

You can use item access to get to the innermost string:

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

or you could loop over all the translations listed (it's a list):

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

as Google's translation service can give more than one translation for a given text.

于 2012-11-30T15:11:40.717 回答