python在命令行下使用google翻譯(帶語音)
說明
1. 使用google翻譯服務(wù)獲得翻譯和語音;
2. 使用mplayer播放獲得的聲音文件,因此,如果要播放語音,請確保PATH中能夠找到mplayer程序,如果沒有mplayer,請將use_tts設(shè)置為False運(yùn)行。即:
main(use_tts=False)
3. 退出程序,輸入"x",回車。
#! /usr/bin/env python
#coding=utf-8
import requests
def translate(words):
import re
url = ("http://translate.google.cn/translate_a/t?"
"client=t&hl=zh-CN&sl=en&tl=zh-CN&ie=UTF-8&oe=UTF-8&oc=1&otf=2&ssel=3&tsel=0&sc=1&q=%s")
ret = requests.get(url % words)
if ret.status_code == 200:
RULE_TRANSLATE = re.compile('''([^\[\]]+?)\]\]''')
match = RULE_TRANSLATE.search(ret.text)
t, o, s, _ = match.group(1).split(u",")
print u"譯文:", t[1:-1]
print u"發(fā)音:", s[1:-1]
print ""
else:
raise Exception("Google翻譯服務(wù)狀態(tài)碼異常。")
def tts(words):
import subprocess
url = "http://translate.google.cn/translate_tts?ie=UTF-8&q=%s&tl=en&total=1&idx=0&textlen=4&prev=input"
ret = requests.get(url % words)
if ret.status_code == 200:
ext = ret.headers["content-type"].split("/")[1]
filename = "tts.%s" % ext
with open(filename, "wb") as f:
f.write(ret.content)
# 不顯示mplayer的輸出
log_file = "./mplayer.log"
with open(log_file, "w") as f:
subprocess.call(["mplayer", filename], stdout=f, stderr=f)
else:
raise Exception("Google TTS服務(wù)狀態(tài)碼異常。")
def main(use_tts=True):
while 1:
#在window下raw_input不能直接提示中文,需要u"中文".encode("gbk")
#為了與平臺無關(guān),這里直接提示"English:"
words = raw_input("English:")
if words == "x":
break
if use_tts:
tts(words)
translate(words)
if __name__ == "__main__":
main(use_tts=True)
- python利用google翻譯方法實(shí)例(翻譯字幕文件)
- Python 實(shí)現(xiàn)的 Google 批量翻譯功能
- 淺談python實(shí)現(xiàn)Google翻譯PDF,解決換行的問題
- python3使用urllib示例取googletranslate(谷歌翻譯)
- python翻譯軟件實(shí)現(xiàn)代碼(使用google api完成)
- Python爬蟲爬取有道實(shí)現(xiàn)翻譯功能
- python 簡單的調(diào)用有道翻譯
- python 爬蟲如何實(shí)現(xiàn)百度翻譯
- python 實(shí)現(xiàn)批量圖片識別并翻譯
- python用tkinter實(shí)現(xiàn)一個(gè)gui的翻譯工具
- python調(diào)用有道智云API實(shí)現(xiàn)文件批量翻譯
- python開發(fā)一款翻譯工具
- python 調(diào)用Google翻譯接口的方法
相關(guān)文章
OpenCV-Python使用分水嶺算法實(shí)現(xiàn)圖像的分割與提取
在圖像的處理過程中,經(jīng)常需要從圖像中將前景對象作為目標(biāo)圖像分割或者提取出來。本文就介紹了使用分水嶺算法實(shí)現(xiàn)圖像的分割與提取,感興趣的可以了解一下2021-06-06
使用TensorFlow直接獲取處理MNIST數(shù)據(jù)方式
今天小編就為大家分享一篇使用TensorFlow直接獲取處理MNIST數(shù)據(jù)方式,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
python調(diào)用c++返回帶成員指針的類指針實(shí)例
今天小編就為大家分享一篇python調(diào)用c++返回帶成員指針的類指針實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
Python入門之三角函數(shù)atan2()函數(shù)詳解
使用Mixin設(shè)計(jì)模式進(jìn)行Python編程的方法講解

