Skip to main content
 首页 » 编程设计

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

2025年05月04日11虾米姐

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

我希望得到任何帮助,我将不胜感激。

请您参考如下方法:

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

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

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

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

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