編寫百度翻譯工具,免得每次開啟網頁
阿新 • • 發佈:2019-01-31
#coding=utf-8 ''' 百度翻譯工具,使用百度翻譯介面進行翻譯,免得每次開啟網頁,這樣直接解析更省力''' import requests import sys import json def utf82u(s): return s.decode("utf-8") def main(): reload(sys) sys.setdefaultencoding("utf-8") trans_arg = '' if len(sys.argv) > 1: trans_arg = sys.argv[1] trans_arg = trans_arg.decode('gbk').encode('utf-8') data={"from":"en", "to":"zh", "query":trans_arg, "transtype":"translang", "simple_means_flag":3, } res = requests.post("http://fanyi.baidu.com/v2transapi", data=data) js = json.loads(res.text) result = u"無結果" if "dict_result"in js: dr = js["dict_result"] if "simple_means" in dr: sm = dr["simple_means"] if "word_means" in sm: wm = sm["word_means"] result = wm if type(result) == list: result = map(utf82u, result) result = ";\n".join(result) eliftype(result) == str: result = utf82u(result) print result if __name__ == '__main__': main()