接前两篇文章:
骚操作,妈妈再也不用担心我看英文文献了 - 1.功能介绍
骚操作,妈妈再也不用担心我看英文文献了 - 2.逻辑+代码
翻译比较简单,有现成的接口,可以看 百度翻译开放平台,注册一个账号,拿到appid和key,代码如下:
(我把账号密码隐藏了)
# -*- coding: utf-8 -*-
#python3
import http.client
import hashlib
import urllib
import random
import json
def _get_password(path="E:\\Program_Files\\英译中朗读女\\password.txt"):
with open(path) as f:
lines = f.readlines()
appid = lines[0].strip()
secretKey = lines[1].strip()
return appid,secretKey
def translateToChinese(q):
appid, secretKey = _get_password()
httpClient = None
myurl = '/api/trans/vip/translate'
fromLang = 'auto' # 原文语种
toLang = 'zh' # 译文语种
salt = random.randint(32768, 65536)
# q= "What's the simplest way of detecting keyboard input in python from the terminal?"
sign = appid + q + str(salt) + secretKey
sign = hashlib.md5(sign.encode()).hexdigest()
myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(
q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
salt) + '&sign=' + sign
try:
httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
httpClient.request('GET', myurl)
# response是HTTPResponse对象
response = httpClient.getresponse()
result_all = response.read().decode("utf-8")
result = json.loads(result_all)
out = result['trans_result'][0]['dst']
return out
except Exception as e:
print(e)
finally:
if httpClient:
httpClient.close()
最后,再把它打包弄成一个bat文件,不然还得打开ide太麻烦。
@echo off
REM 声明采用UTF-8编码
chcp 65001
echo note
echo 选中中文,按下f1键直接朗读。
echo note
echo 选中英文,按下f2键先翻译成中文,再进行朗读。
python E:\Program_Files\英译中朗读女\auto_read_by_chinese.py
@cmd.exe
酱紫,就完成了。是不是很简单,但很有用呀。你想想,看着英文,按一个键,就可以朗读对应的中文了,这还不爽吗?
看英文系列【全】:
骚操作,妈妈再也不用担心我看英文文献了 - 1.功能介绍
骚操作,妈妈再也不用担心我看英文文献了 - 2.逻辑+代码
骚操作,妈妈再也不用担心我看英文文献了 - 3.翻译接口+打包执行
源码连接:
https://github.com/JizhiXiang/bestEngToChiSpeaker
【感觉有意思,点个赞呗,算对我分享东西的肯定,thx】