Python實(shí)現(xiàn)有道翻譯+語音播報(bào)

有道翻譯

調(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)了一個(gè)簡單的翻譯功能很簡便吧。

下面我們來添加一個(gè)語音功能
要實(shí)現(xiàn)這個(gè)功能需要調(diào)用pyttsx3 這個(gè)庫,我的運(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)

# 語音播報(bào)
def engine(voice):
    engine = pyttsx3.init()
    engine.say(voice)
    engine.runAndWait()

if __name__ == "__main__":
    main()

附:pyttsx3的官文文檔

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容