Python USES Google translate of with voice at the command line

  • 2020-04-02 13:22:56
  • OfStack

instructions

1. Use Google translation service for translation and voice;
2. Use mplayer to play the acquired sound file, so if you want to play the voice, make sure the mplayer program is found in the PATH. If you do not have mplayer, set use_tts to False to run. That is:
The main (use_tts = False)
3. Exit the program, type "x" and press enter.


#! /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" The 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)
        #  Don't show mplayer The output of the 
        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:
        # in window Under the raw_input Cannot prompt Chinese directly, need u" Chinese ".encode("gbk")
        # To be platform agnostic, here is the direct hint "English:"
        words = raw_input("English:")
        if words == "x":
            break
        if use_tts:
            tts(words)
        translate(words)

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


Related articles: