python200行代码实现一个翻译软件
心血来潮写一个命令行的翻译软件方便使用(基于百度翻译api), 话不多说上代码-_-
支持从文件输入输出
支持从剪切板输入输出
#!/home/fyang/.virtualenvs/base/bin/python
import requests
import random
import hashlib
import json
import urllib
import pyperclip
from sys import exit
from optparse import OptionParser
APP_ID="**********"
KEY="**********"
# global option
class Conf:
DEFAULT = 1 # stanted
FILE = 2 # file
CLIPBOARD = 3 # clipboard
langs = {
"en": "英文",
"zh": "中文",
"yue": "粤语",
"wyw": "文言文",
"jp": "日语",
"kor": "韩语",
"fra": "法语",
"spa": "西班牙语",
"th": "泰语",
"ara": "阿拉伯语",
"ru": "俄语",
"pt": "葡萄牙语",
"de": "德语",
"it": "意大利语",
"el": "希腊语",
"nl": "荷兰语",
"pl": "波兰语",
"bul": "保加利亚语",
"est": "爱沙尼亚语",
"dan": "丹麦语",
"fin": "芬兰语",
"cs": "捷克语",
"rom": "罗马尼亚语",
"slo": "斯洛文尼亚语",
"swe": "瑞典语",
"hu": "匈牙利语",
"cht": "繁体中文",
"vie": "越南语"
}
SYS_IN = DEFAULT
SYS_OUT = DEFAULT
trans_from = "en"
trans_to = "zh"
query_str = ""
input_file = ""
output_file = ""
def printArgs():
print(Conf.SYS_IN)
print(Conf.SYS_OUT)
print(Conf.trans_from)
print(Conf.trans_to)
print(Conf.query_str)
print(Conf.input_file)
print(Conf.output_file)
def main():
# init
option_handle()
# start query
query()
def option_handle():
usage = "usage: %prog [option] arg"
opt_parser = OptionParser()
opt_parser.add_option(
"-f", "--from",
dest="trans_from",
default="en",
help="default=en\t\t\t\t\ten...english zh...chinese --list show all language code."
)
opt_parser.add_option(
"-t", "--to",
dest="trans_to",
default="zh",
help="default=zh\t\t\t\t\ten...english zh...chinese. --list show all language code."
)
opt_parser.add_option(
"-p", "--paste",
action="store_true",
dest="paste",
help="use cilpboard content."
)
opt_parser.add_option(
"-i", "--inputfile",
dest="in_file",
help="type file path to input."
)
opt_parser.add_option(
"-o", "--outputfile",
dest="out_file",
help="type file path to output."
)
opt_parser.add_option(
"-q", "--query",
dest="query_str",
help="translate content."
)
opt_parser.add_option(
"-c", "--clipboard",
dest="copy",
action="store_true",
help="output to clipboard."
)
opt_parser.add_option(
"-l", "--list",
dest="list_all",
action="store_true",
help="show all language code."
)
(options, args) = opt_parser.parse_args()
if options.list_all:
print("all language code: ")
for k, v in Conf.langs.items():
print(k, " ", v)
exit(0)
if len(args) > 1:
opt_parser.error("incorrent number of arguments")
exit(0)
# from
if options.trans_from not in list(Conf.langs.keys()):
opt_parser.error("invalid translate_from language code. --list show all code")
exit(0)
Conf.trans_from = options.trans_from
# to
if options.trans_to not in list(Conf.langs.keys()):
opt_parser.error("invalid translata_to language code. --list show all code")
exit(0)
Conf.trans_to = options.trans_to
# query
if len(args) == 1:
Conf.query_str = args[0]
elif options.paste:
Conf.SYS_IN = Conf.CLIPBOARD
Conf.query_str = pyperclip.paste()
elif options.in_file:
Conf.SYS_IN = Conf.FILE
Conf.input_file = options.in_file
try:
with open(Conf.input_file, "r+") as in_file:
for line in in_file.readlines():
Conf.query_str += line.replace("\n", " ")
except:
opt_parser.error("\n[error]: No such file: " + options.in_file)
else:
Conf.SYS_IN = Conf.CLIPBOARD
Conf.query_str = pyperclip.paste()
# out
if options.copy:
Conf.SYS_OUT = Conf.CLIPBOARD
elif options.out_file:
Conf.SYS_OUT = Conf.FILE
Conf.output_file = options.out_file
else:
# Conf.SYS_OUT = Conf.DEFAULT
pass
def query() -> dict:
try:
resp = requests.get(url_handle(Conf.query_str, Conf.trans_from, Conf.trans_to), timeout=5)
print_result(json.loads(resp.content))
except requests.RequestException:
print("[error] network is too slow.")
exit(0)
def url_handle(query_str: str, _from: str, _to: str) -> str:
#
base_url = "https://fanyi-api.baidu.com/api/trans/vip/translate?"
form_data = {
"q": query_str,
"from": _from,
"to": _to,
"appid": APP_ID,
"salt": str(random.randint(1000000, 99999999))
}
form_data['sign'] = get_md5_token(APP_ID + form_data["q"] + form_data["salt"] + KEY)
form_data['q'] = urllib.parse.quote(form_data['q'])
for k, v in form_data.items():
base_url += k + "=" + v + "&"
return base_url[:-1]
def print_result(data: dict):
try:
source_str = data['trans_result'][0]['src']
dest_str = data['trans_result'][0]['dst']
except Exception:
print("[error] please check your arguments and try again.")
exit(0)
if Conf.SYS_OUT == Conf.DEFAULT:
print("[source]: ", source_str)
print("[dest]: ", dest_str)
elif Conf.SYS_OUT == Conf.FILE:
try:
with open(Conf.output_file, "w+") as of:
of.write("[source]\n")
of.write(source_str + "\n")
of.write("[dest]\n")
of.write(dest_str)
except PermissionError:
print("[error] Permission denied: ", Conf.output_file)
else:
pyperclip.copy(dest_str)
def get_md5_token(key: str) -> str:
_md5 = hashlib.md5()
_md5.update(key.encode("utf-8"))
return _md5.hexdigest()
if __name__ == '__main__':
main()
原文:https://www.cnblogs.com/blogfyang/p/12180253.html