python在命令行下使用google翻译(带语音)

yipeiwu_com6年前Python基础

说明

1. 使用google翻译服务获得翻译和语音;
2. 使用mplayer播放获得的声音文件,因此,如果要播放语音,请确保PATH中能够找到mplayer程序,如果没有mplayer,请将use_tts设置为False运行。即:
main(use_tts=False)
3. 退出程序,输入"x",回车。

复制代码 代码如下:

#! /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"译文:", t[1:-1]
        print u"发音:", s[1:-1]
        print ""
    else:
        raise Exception("Google翻译服务状态码异常。")

 

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)
        # 不显示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服务状态码异常。")


def main(use_tts=True):
    while 1:
        #在window下raw_input不能直接提示中文,需要u"中文".encode("gbk")
        #为了与平台无关,这里直接提示"English:"
        words = raw_input("English:")
        if words == "x":
            break
        if use_tts:
            tts(words)
        translate(words)


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

相关文章

Python中列表与元组的乘法操作示例

本文实例讲述了Python中列表与元组的乘法操作。分享给大家供大家参考,具体如下: 直接上code吧,还可以这么玩儿 列表乘法: li=[1,] li=li*3 print(li)...

python3 读写文件换行符的方法

最近在处理文本文件时,遇到编码格式和换行符的问题。 基本上都是GBK 和 UTF-8 编码的文本文件,但是python3 中默认的都是按照 utf-8 来打开。用不正确的编码参数打开,在...

浅析Python中的getattr(),setattr(),delattr(),hasattr()

getattr()函数是Python自省的核心函数,具体使用大体如下: 获取对象引用getattr Getattr用于返回一个对象属性,或者方法 class A: def __i...

Python实现程序判断季节的代码示例

Python实现程序判断季节的代码示例

1.用户输入月份,判断这个月是哪个季节 month = int(input('Month:')) if month in [3,4,5]: print('春季') elif mo...

Python实现多线程下载文件的代码实例

实现简单的多线程下载,需要关注如下几点:1.文件的大小:可以从reponse header中提取,如“Content-Length:911”表示大小是911字节2.任务拆分:指定各个线程...