python 单词翻译小工具

来源:互联网 发布:w7旗舰版系统优化教程 编辑:程序博客网 时间:2024/04/28 20:24

附件提供了一个win编译的exe版本,用py2exe编译。
linux下直接输入文件名即可。

下载文件以及源码请到:http://www.chinaunix.net/index.php?uid=386791&url=http://bbs.chinaunix.net/viewthread.php?tid=1256415

linux编码为utf-8,win编码为gbk

linux 代码:

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

# *************************************************
# author   :   smallfish <smallfish.xy@gmail.com>
#              http://hi.baidu.com/smallfish_xy
# date     :   2008-08-28
# version :   0.1
# desc     :   返回输入单词的中文翻译
# *************************************************

# 导入sys urllib re模块相应的常量和函数
from sys import argv
from urllib import urlopen
from re import S, sub, compile

# 格式化结果 去除换行、替换空格和html标签
def format_html(s):
     s = sub("/s+", ' ', s)
     s = sub("&nbsp;", ' ', s)
     s = sub("<[^>]*>", '', s)
     return s

# 发送查询
def search_word(word) :
     searchurl = 'http://dict.yodao.com/search?tab=chn&keyfrom=dict.top&btnG=&q='
     html = urlopen(searchurl+str(word)).read()
     # 正则匹配结果
     results = compile('<td class="attributem1web">(.*?)</td>', S).findall(html)
     # 输出结果
     if not results :
          print '没有查询到结果'
          return
     for result in results :
          print format_html(result)

print '# 这是一个用python写的翻译的小程序 作者:smallfish 邮件:smallfish@live.cn'
print '# 输入需要翻译的单词 比如 >>> fish 输入q!退出本程序'
input = raw_input('>>> ')
while input != 'q!' :
search_word(input)
input = raw_input('>>> ')

原创粉丝点击