專案練習:百度翻譯小程式
阿新 • • 發佈:2018-11-28
1 # -*- coding:utf-8 -*- 2 # Author:Sure Feng 3 4 import requests 5 import json 6 import sys 7 8 class BaiduFanyi(object): 9 def __init__(self, trans_str): 10 self.trans_str = trans_str 11 self.lang_detect_url = "https://fanyi.baidu.com/langdetect" 12 self.trans_url = "https://fanyi.baidu.com/basetrans" 13 self.headers = {"User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Mobile Safari/537.36"} 14 15 def parse_url(self, url, data): 16 """解析URL地址,返回響應內容(dict 格式的)""" 17 r = requests.post(url=url, data=data, headers = self.headers)18 return json.loads(r.content.decode()) # 把Json格式的字串轉換為字典 19 20 def get_ret(self, dict_respond): 21 """提取翻譯結果""" 22 trans_ret = dict_respond["trans"][0]["dst"] 23 print("result is: ", trans_ret) 24 25 def run(self): 26 27 # 1 獲取語言型別 28 # 1.1 準備post的URL地址,data資料29 lang_detect_data = {"query": self.trans_str} 30 # 1.2 傳送請求,獲取語言型別 31 lang = self.parse_url(self.lang_detect_url, lang_detect_data)["lan"] 32 # 2 準備post請求資料 33 trans_data = {"query": self.trans_str, "from": "zh", "to": "en"} if lang == "zh" else \ 34 {"query": self.trans_str, "from": "en", "to": "zh"} 35 # 3 傳送請求,獲取響應資料 36 dict_respond = self.parse_url(self.trans_url, trans_data) 37 # 4 提取翻譯結果 38 self.get_ret(dict_respond) 39 40 if __name__ == "__main__": 41 # trans_str = sys.argv[1] 42 trans_str = input("what would you want to translate>>>") 43 baidu_fanyi = BaiduFanyi(trans_str) 44 baidu_fanyi.run()