码迷,mamicode.com
首页 > 编程语言 > 详细

Python 调用百度翻译API

时间:2014-09-30 16:23:39      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   strong   sp   

    由于实习公司这边做的是日文app,有时要看看用户反馈,对于我这种五十音图都没记住的人,表示百度翻译确实还可以。但不想每次都复制粘贴啊,google被墙也是挺蛋疼的事,所以用python结合baidu api 整了一下,和大家分享。

    1.百度翻译api

  由于百度翻译api需要用到API key,所以,得注册百度开发者账号,然后创建开发者服务工程,得到的授权API key,具体操作可查看官方文档,请点 百度翻译api

  2.代码实现

  基本思路是:先将用户反馈抓下来,然后再处理html标签,再调用百度翻译api,将用户反馈内容(日文)翻译成中文,这里贴一段百度翻译的代码。

# -*- coding: utf-8 -*- 
import string
import re,os
import json
import urllib2
import sys  
reload(sys)  
sys.setdefaultencoding(utf-8) 

#调用baidu翻译api
def trans_baidu(src):    

    ApiKey = "XXXXXXXXXXXXXXXXXXX"#百度开发者apikey
    turl = "http://openapi.baidu.com/public/2.0/bmt/translate?client_id="+ApiKey+"&q="+src+"&from=auto&to=zh"
    
    try:
        req = urllib2.Request(turl)
        con = urllib2.urlopen(req).read()
    except Exception, e:
        raise e
    else:    
        decoded = json.loads(con)
        dst = str(decoded["trans_result"][0]["dst"])
        return dst

def main():
    while True:
        word = raw_input(Input the word you want to search:)
        print "translate.........."    
        target = trans_baidu(word)
        print target

if __name__ == __main__:
    main()

 

Python 调用百度翻译API

标签:style   blog   http   color   io   os   ar   strong   sp   

原文地址:http://www.cnblogs.com/chenbjin/p/4001998.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!