Python uses Google Translate (with voice) on the command line

Source: Internet
Author: User
Description

1. Use Google translation services to obtain translations and voice;
2. Use MPlayer to play the resulting sound file, so if you want to play the voice, make sure that the MPlayer program is found in path, and if there is no mplayer, set the Use_tts to False to run. That
Main (Use_tts=false)
3. Exit the program, enter "X" and return.

Copy the 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 Translate 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 display the output of the 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 Service status code is abnormal. ")


def main (use_tts=true):
While 1:
#在window下raw_input不能直接提示中文, you need U "Chinese". Encode ("GBK")
#为了与平台无关, there is a direct "中文版:"
Words = Raw_input ("中文版:")
if words = = "X":
Break
If Use_tts:
TTS (words)
Translate (words)


if __name__ = = "__main__":
Main (Use_tts=true)

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.