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

时间:2023-06-02 13:47:17 

说明

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)

标签:google翻译,命令行
0
投稿

猜你喜欢

  • 一文吃透Go的内置RPC原理

    2024-02-03 08:45:53
  • vue3.0语法糖内的defineProps及defineEmits解析

    2024-05-09 09:25:43
  • 关于Python中异常(Exception)的汇总

    2022-11-29 05:42:15
  • MySQL Administrator 登录报错的解决方法

    2024-01-21 06:53:06
  • Python常用的内置序列结构(列表、元组、字典)学习笔记

    2021-02-18 21:25:45
  • 在SQL Server中实现最短路径搜索的解决方法

    2024-01-24 13:47:10
  • mysql数据库 主从复制的配置方法

    2024-01-16 09:24:35
  • python 合并表格详解

    2023-09-08 16:03:48
  • js+html5通过canvas指定开始和结束点绘制线条的方法

    2024-05-02 17:20:44
  • pytorch之torchvision.transforms图像变换实例

    2021-05-19 05:44:05
  • php封装json通信接口详解及实例

    2023-11-14 21:56:26
  • 分享Python 的24个编程超好用技巧

    2021-05-21 16:51:55
  • 三种SQL分页查询的存储过程代码

    2012-01-05 19:31:32
  • Go编写定时器与定时任务详解(附第三方库gocron用法)

    2024-05-09 09:40:19
  • pytorch permute维度转换方法

    2023-09-07 17:49:32
  • 解决os.path.isdir() 判断文件夹却返回false的问题

    2022-11-07 18:11:37
  • asp如何用Jmail组件的发送电子邮件?

    2010-06-12 12:51:00
  • 精致的web设计

    2009-12-04 19:07:00
  • Hibernate Oracle sequence的使用技巧

    2009-06-19 17:25:00
  • Python中的enum的使用方法

    2023-10-17 16:59:24
  • asp之家 网络编程 m.aspxhome.com