有道翻譯
調(diào)用有道翻譯的接口(用谷歌瀏覽器打開有道翻譯-開發(fā)者-開發(fā)者工具-查找接口)話不多說上代碼
def main():
word = input('請輸入翻譯的內(nèi)容:')
url = 'http://fanyi.youdao.com/translate'
data = {'i': word, 'doctype':'json'}
header = {'User-Agent': 'Mozilla/5.0'}
response = requests.post(url, data=data, headers = header)
print(response.json()['translateResult'][0][0]['tgt'])
if __name__ == "__main__":
main()
這幾行代碼就實(shí)現(xiàn)了一個簡單的翻譯功能很簡便吧。
語音功能
要實(shí)現(xiàn)這個功能需要調(diào)用pyttsx3 這個庫谍婉,我的運(yùn)行環(huán)境是python3
安裝命令:
pip install pyttsx3
代碼實(shí)現(xiàn)
import requests
import pyttsx3
def main():
word = input('請輸入翻譯的內(nèi)容:')
url = 'http://fanyi.youdao.com/translate'
data = {'i': word,
'doctype':'json'}
header = {'User-Agent': 'Mozilla/5.0'}
response = requests.post(url, data=data, headers = header)
voice = response.json()['translateResult'][0][0]['tgt']
print(voice)
engine(voice)
# 語音播報
def engine(voice):
engine = pyttsx3.init()
engine.say(voice)
engine.runAndWait()
if __name__ == "__main__":
main()