This article describes how to use google translation to obtain translation and speech.
1. use the google translation service to obtain translation and speech;
2. use mplayer to play the obtained audio file. Therefore, if you want to play the voice, make sure that the mplayer program can be found in the PATH. if there is no mplayer, set use_tts to False to run the program. That is:
Main (use_tts = False)
3. exit the program, enter "x", and press enter.
The code is 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 ("the Google translation service status code is abnormal. ")
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)
# Do not display mplayer output
Log_file = "./mplayer. log"
With open (log_file, "w") as f:
Subprocess. call (["mplayer", filename], stdout = f, stderr = f)
Else:
Raise Exception ("The Google TTS service status code is abnormal. ")
Def main (use_tts = True ):
While 1:
# In the window, raw_input cannot directly prompt Chinese characters. u "Chinese". encode ("gbk") is required ")
# In order to be irrelevant to the platform, the following prompt is displayed: "English :"
Words = raw_input ("English :")
If words = "x ":
Break
If use_tts:
Tts (words)
Translate (words)
If _ name _ = "_ main __":
Main (use_tts = True)