Description
1. Use of Google translation services to obtain translations and voice;
2. Use MPlayer to play the resulting sound file, so if you want to play voice, make sure that the MPlayer program is found in the path, and if there is no mplayer, set the Use_tts to False. That
Main (Use_tts=false)
3. Exit the program, enter "X" and return.
Copy Code code as follows:
#! /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 "translation:", t[1:-1]
Print U "pronunciation:", s[1:-1]
Print ""
Else
Raise Exception ("Google Translation Service status code exception.") ")
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)
# does not show MPlayer output
Log_file = "./mplayer.log"
With open (Log_file, "w") as F:
Subprocess.call (["MPlayer", filename], stdout=f, stderr=f)
Else
Raise Exception ("Google TTS Service Status code exception.") ")
def main (use_tts=true):
While 1:
#在window下raw_input不能直接提示中文, you need "Chinese". Encode ("GBK")
#为了与平台无关, here is a direct hint "中文版:"
Words = Raw_input ("中文版:")
if words = = "X":
Break
If Use_tts:
TTS (words)
Translate (words)
if __name__ = = "__main__":
Main (Use_tts=true)