python:单词翻译工具(urllib库的使用举例)
linux编码为utf-8,win编码为gbk
#!/usr/bin/python
#coding:utf-8
# *************************************************
# Usage : online translation by python
# date : 2008-11-28
# version : 0.1
# *************************************************
- # 导入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(" ", ' ', 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 '# 输入需要翻译的单词 比如 >>> 输入q!退出本程序'
- input = raw_input('>>> ')
- while input != 'q!' :
- search_word(input)
- input = raw_input('>>> ')
没有评论▼