不知道错误在那,求
import json
import requests
class Baidu_translator():
def __init__(self, troms_str):
self.lang_detect_url = "https://fanyi.baidu.com/langdetect"
self.troms_str = troms_str
self.headers = {
"User-agent ": "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1"}
self.trans_url = "https://fanyi.baidu.com/basetrans"
def get_ret(self, dict_response): # 提取翻译结果
ret = dict_response["trans"][0]["dst"]
return ret
def parse_url(self, url, data): # 发送post请求 获取响应
response = requests.post(url, data=data, headers=self.headers)
# 默认解码utf-8
print(response.content.decode())
return json.loads(response.content.decode())
def run(self): # 实现主要逻辑
# 获取语言类型
# 准备post的url地址post_data
lang_detect_data = {"query": self.troms_str}
# 发送post请求,获得响应 # 提取语言类型
lang = self.parse_url(self.lang_detect_url, lang_detect_data)["lan"]
# 准备post数据
troms_data = {
"query": self.troms_str,
"from": "zh",
"to": "en"
} if lang == "zh" else {
"query": self.troms_str,
"from": "en",
"to": "zh"
}
# 发送post请求 获取响应
dict_response = self.parse_url(self.trans_url, troms_data)
# 提取翻译的结果
ret = self.get_ret(dict_response)
print(ret)
if __name__ == '__main__':
troms_str = input("输入要翻译的:")
baidu_translator = Baidu_translator(troms_str)
baidu_translator.run()