show

1. Use Google translation services and voice;
2. The use of the mplayer sound files, therefore, if you want to play the voice, please make sure that the PATH mplayer can be found in the program, if there is no mplayer, please send use_tts set to False. (i.e.,
the main use_tts=False)
3. Exit the program, enter "x", press enter.


code is as follows:


#! The/usr/bin/env python
#coding=utf-8

import requests


def translate (words) :
      The import re
      Url=(" http://translate.google.cn/translate_a/t? "
     " client=t&hl=useful - CN&sl=en&tl=useful - CN&ie=utf-8 &oe=utf-8 &oc=1 &2 &ssel otf==3 &tsel=0=1 &sc &q=% s ")
      Ret=requests. Get (url % words)
      If ret. Status_code==200:
              Running the RULE_TRANSLATE=re.com (" '([^ \ [\]] +?) \] \]' ' ')
              Match=RULE_TRANSLATE. Search (ret. Text)
              T, o, s, _=match. The group (1). The split (u) ", "
              Print u ", "t [1, 1]
              Print u "pronunciation", s [1, 1]
              Print "
"       The else:
              Raise the Exception (" Google translation service abnormal status code. ")

 

def TTS (words) :
      The 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 [r]. "the content-type" split ("/") [1]
              Filename="TTS. % s" % ext
              With the open (filename, "wb") as f:
                      F.w rite (ret. Content)
              #don't show the output of the mplayer
              Log_file="./mplayer. Log "
              With the open (log_file, "w") as f:
                      Subprocess. Call ([" mplayer ", filename], stdout=f, stderr=f)
      The else:
              Raise the Exception (" Google TTS service abnormal status code. ")


def main (use_tts=True) :
      While 1:
              #raw_input cannot directly under Windows prompt Chinese, need u "Chinese". Encode (" GBK ")
              #in order to have nothing to do with platform, here directly prompt "English:
"               English: words=raw_input (" ")
              If words=="x" :
                      To break
              If use_tts:
                      TTS (words)
              Translate (words)


if __name__=="__main__" :
      The main (use_tts=True)


This concludes the body part