« »
2008-11-29Python

95

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
# *************************************************

  1. # 导入sys urllib re模块相应的常量和函数
  2. from sys import argv
  3. from urllib import urlopen
  4. from re import S, sub, compile
  5.  
  6. # 格式化结果 去除换行、替换空格和html标签
  7. def format_html(s):
  8.     s = sub("\s+", ' ', s)
  9.     s = sub(" ", ' ', s)
  10.     s = sub("<[^>]*>", '', s)
  11.     return s
  12.  
  13. # 发送查询
  14. def search_word(word) :
  15.     searchurl = 'http://dict.yodao.com/search?tab=chn&keyfrom=dict.top&btnG=&q='
  16.     html = urlopen(searchurl+str(word)).read()
  17.     # 正则匹配结果
  18.     results = compile('<td class="attributem1web">(.*?)</td>', S).findall(html)
  19.     # 输出结果
  20.     if not results :
  21.         print '没有查询到结果'
  22.         return
  23.     for result in results :
  24.         print format_html(result)
  25.  
  26. print '# 输入需要翻译的单词 比如 >>> 输入q!退出本程序'
  27. input = raw_input('>>> ')
  28. while input != 'q!' :
  29.     search_word(input)
  30.     input = raw_input('>>> ')

您还可能感兴趣的内容

日志信息 »

该日志于2008-11-29 11:36由 admin 发表在Python分类下, 你可以发表评论。除了可以将这个日志以保留源地址及作者的情况下引用到你的网站或博客,还可以通过RSS 2.0订阅这个日志的所有评论。

没有评论

发表评论 »


返回顶部