# -*- coding: utf-8 -*- # @Author : FELIX # @Date : 2018/4/29 18:25 import requests import json def translate(content, tolang='zh', fromlang=None): dates = { ' query ' : content, } #Automatically get the language type if not fromlang: fromlang = json.loads(requests.post('http://fanyi.baidu.com/langdetect', data=datas).text)['lan'] # print(fromlang) data = { 'from': fromlang, 'to': tolang, 'query': content, } url = ' http://fanyi.baidu.com/basetrans ' headers = { 'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Mobile Safari/537.36', } try: res = requests.post(url=url, data=data, headers=headers) # print(res.text) result = json.loads(res.text) return result['trans'][0]['dst'] except Exception as e: print('翻译出错') print(e) ''' en Chinese en English yue Cantonese wyw classical Chinese jp Japanese kor Korean fra French spa spanish th Thai ara Arabic ru in Russian pt portuguese de german it italian el Greek nl dutch pl Polish bul Bulgarian est Estonian dan Danish fin Finnish cs czech rom Romanian slo Slovenian swe Swedish hu Hungarian cht Traditional Chinese vie Vietnamese ''' # print(translate('What are you doing?', 'wyw')) # print(translate('What are you doing?', 'zh', 'en')) print(translate('hello girls', 'wyw', 'en'))