这个程序可以实现中英文的自动识别然后进行翻译
看着程序就很好理解。
import requests
import json
class Translation():
'''翻译'''
def __init__(self,content):
self.content = content
self.url = "http://fanyi.baidu.com/basetrans"
self.headers = {"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1"}
def langdetect(self):
detect_url = "http://fanyi.baidu.com/langdetect"
detect_data = {"query": self.content}
response = requests.post(detect_url,data = detect_data,headers = self.headers)
detect = response.content.decode()
detect_json = json.loads(detect)['lan']
if detect_json =='en':
data = {"query": self.content,"from": "en","to": "zh"}
else:
data = {"query":self.content,"from": "zh","to": "en"}
return data
def requests_data(self,data):
url = "http://fanyi.baidu.com/basetrans"
response = requests.post(url,data=data,headers =self.headers)
return response
def parse_data(self,response):
html_str = response.content.decode()
print("翻译结果是:",json.loads(html_str)["trans"][0]["dst"])
def run(self):
data = self.langdetect()
response = self.requests_data(data)
self.parse_data(response)
if __name__ == '__main__':
content = input("请输入要翻译的内容:")
translation =Translation(content)
translation.run()