Python脚本翻译英文到汉语

来源:互联网 发布:北京赛车数据接入 编辑:程序博客网 时间:2024/06/10 03:27
下载的词典没找到几个好用的,就想能不能用脚本终端简单的实现呢。结果到网上找了一圈,有几个网友的也在做这件事情。参考他们的成果,做了一些改动。


创建完python文件后,创建个软链接到$PATH路径中,就可以直接输入脚本名字加上要翻译的英文了。这里使用的Google的翻译服务。直接句子翻译。
效果:


Ian@ubuntuex:~$ dict
Press 'q' to exit
->hello world
你好世界
->hello
你好
->q
Ian@ubuntuex:~$ dict hello world
你好世界
Ian@ubuntuex:~$
详细的代码如下,点击此处Python for google translate from english to chinese下载:


#!/usr/bin/env python
# -*- coding: utf-8 -*-


'''
Translate English to Chinese use Google Translate web service.


Usage:
Change this Python file to dict.py or other names, then you should
may a soft link to usr/local/bin like this:
sudo ln -s /this/file/path/dict.py /usr/local/bin/dict


==========
dict EnglistWorld1 EnglishWorld2


**OR**


dict
then input english world


Author: ian@ibuo.org
Date: 2012-8-4


'''


import sys
import urllib,urllib2
from BeautifulSoup import BeautifulSoup


def GoogleTranslate(text):


    values={'hl':'zh-CN','ie':'utf8','text':text,'langpair':"en|zh-CN"}
    url='http://translate.google.cn/translate_t'


    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    req.add_header('User-Agent', 
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)")


    response = urllib2.urlopen(req)


    html_all = BeautifulSoup(''.join(response.read()))


    html_result = html_all.findAll("span",{"id":"result_box"})


    '''
    <span id="result_box" class="short_text">
    <span title="hello" onmouseover="this.style.backgroundColor='#ebeff9'" 
    onmouseout="this.style.backgroundColor='#fff'">
    u'你好'
    /span>
    </span>
    '''
    try:
        html_final = html_result[0].findAll('span')
        print html_final[0].string
    except Exception, e:
        print "Exit caused by:", e
        exit(1)


if len(sys.argv)>=2:
    text = ' '.join(sys.argv[1:]) # ['hello', 'world'] to 'hello world'
    GoogleTranslate(text)
else:
    print "Press 'q' to exit"
    while True:
        text = raw_input("->")
        if text=='q':
            break;


        GoogleTranslate(text)
参考:


作者 Leyond:Google翻译之Python篇


 Posted by ian at 02:13  Tagged with: Python
原创粉丝点击