python3调用百度翻译api的命令行翻译工具

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

#! /usr/bin/env python3
#coding=utf-8
import sys
import json
import urllib.request
import urllib.parse
import http.client
from io import StringIO

TRANS_URL='http://fanyi.baidu.com/v2transapi'
ORIGIN_HOST='fanyi.baidu.com'

class Result:
	def __init__(self, src, dest, meanings=None):
		self.src=src
		self.dest=dest
		self.meanings=meanings

	def parse_from_json(json_data):
		trans_data=json_data['trans_result']['data'][0]
		try:
			dict_data=json_data['dict_result']['simple_means']['symbols'][0]['parts']
			means=list()
			for item in dict_data:
				tmp=item['means']
				if isinstance(tmp[0],dict):
					for t_item in tmp:
						means.append(t_item['word_mean'])
				else:
					means.append(tmp)
		except KeyError:
			means=None
		return Result(trans_data['src'],trans_data['dst'],means)

	def show(self,file=sys.stdout):
		str_template='<<<translate\n%s--->%s\n<<<meaning\n%s'
		print(str_template % (self.src, self.dest, self.meanings))

	
def handle_result(content):
	json_data=json.loads(content)
	Result.parse_from_json(json_data).show()

def compose_request(word):
	r"""
	compose urllib.request.Request object accordingly
	
	"""
	body=StringIO()
	body.write('from=en&to=zh' if is_eng(word) else 'from=zh&to=en')
	body.write('&')
	body.write(urllib.parse.urlencode({'query': word }, encoding='utf-8'))
	body.write('&transtype=trans&simple_means_flag=3')
	body=body.getvalue()

	headers={'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
		'X-Requested-With':'XMLHttpRequest'
		}
	return urllib.request.Request(TRANS_URL, body.encode(encoding='utf-8'), headers=headers, origin_req_host=ORIGIN_HOST, method='POST')

def is_eng(word):
	r"""
	determine whether the unicode char is english or not

	>>> is_eng('hello')
	True

	>>> is_eng('你好')
	False

	>>> is_eng('\'')
	True

	>>> is_eng('‘')
	False

	"""
	for uchar in word:
		if len(uchar.encode('utf-8'))==1:
			continue
		else:
			return False
	return True

if __name__ == '__main__':
	if len(sys.argv)<2:
		print('Usage: %s word_to_translate' % sys.argv[0])
		sys.exit(0)
	word=sys.argv[1]
	resp=urllib.request.urlopen(compose_request(word))
	if(resp.status==200):
		handle_result(resp.read().decode('utf-8'))
	else:
		print('Rquest Error: \n HTTP Status: %d \n Reason: %s \n', resp.status, resp.reason)