+ -
当前位置:首页 → 问答吧 → 闲来无事,用Python写个翻译工具

闲来无事,用Python写个翻译工具

时间:2011-03-15

来源:互联网

在英语词典方面,Linux环境下的软件远不及Win环境下,由于工作一般都在Linux环境下,并且希望在堆码的时候不用离开vim编辑器,于是花了一点时间写了个翻译的小工具,主要方便我在Linux环境下遇到不认识的英语单词时充当翻译小助手。这个小工具使用Python语言编写完成,其中使用到这些类库(urllib,BeautifulSoup ),前者主要负责网络通讯方面,后者负责HTML的解析。这也是Python语言生态圈的强大之处,写个这样的小工具,毫不费力。
在线翻译的原理:首先根据用户输入的单词提交给百度词典 ,其次读取百度词典返回的数据并解析,最后将处理过的数据显示给用户。以下是该工具的具体代码(Translate.py):
  1. import urllib
  2. import codecs
  3. from BeautifulSoup import BeautifulSoup
  4. from sys import argv
  5. import re,time

  6. class Translate:
  7.     def Start(self):
  8.         self._get_html_sourse()
  9.         self._get_content("enc")
  10.         self._remove_tag()
  11.         self.print_result()

  12.     def _get_html_sourse(self):
  13.         word=argv[1] if len(argv)>1 else ''
  14.         url="http://dict.baidu.com/s?wd=%s&tn=dict" %  word
  15.         self.htmlsourse=unicode(urllib.urlopen(url).read(),"gb2312","ignore").encode("utf-8","ignore")

  16.     def _get_content(self,div_id):
  17.         soup=BeautifulSoup("".join(self.htmlsourse))
  18.         self.data=str(soup.find("div",{"id":div_id}))

  19.     def _remove_tag(self):
  20.         soup=BeautifulSoup(self.data)
  21.         self.outtext=''.join([element  for element in soup.recursiveChildGenerator() if isinstance(element,unicode)])

  22.     def print_result(self):
  23.         for item in range(1,10):
  24.             self.outtext=self.outtext.replace(str(item),"\n%s" % str(item))
  25.         self.outtext=self.outtext.replace("  ","\n")
  26.         print self.outtext

  27. if __name__=="__main__":
  28.      Translate().Start()
复制代码

作者: boy11-2   发布时间: 2011-03-15

如果您的运行环境安装了BeautifulSoup类库,那么执行类似这样的命令ython Translate.py computer,您将会看到下面这样的结果:


后记,目前这个小工具在输出排版方面还不太满意。

作者: boy11-2   发布时间: 2011-03-15

热门下载

更多