• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

python在线抓取百度词典的翻译结果翻译单词

python 水墨上仙 2712次浏览

这段代码通过抓取百度词典的翻译结果达到翻译单词的目的

代码转自:http://www.iteye.com/topic/819440

这个小工具使用Python语言编写完成,其中使用到这 些类库(urllib,BeautifulSoup ),前者主要负责网络通讯方面,后者负责HTML的解析。这也是Python语言生态圈的强大之处,写个这样的小工具,毫不费力。

在线翻译的原理:首先根据用户输入的单词提交给百度词典 ,其次读取百度词典返回的数据并解析,最后将处理过的数据显示给用户。以下是该工具的具体代码(Translate.py)

import urllib
import codecs
from BeautifulSoup import BeautifulSoup
from sys import argv
import re,time

class Translate:
    def Start(self):
        self._get_html_sourse()
        self._get_content("enc")
        self._remove_tag()
        self.print_result()

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

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

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

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

#from 75271.com
if __name__=="__main__":
     Translate().Start()


喜欢 (0)
加载中……