源自: http://www.cnblogs.com/cbbukn/archive/2010/11/22/1883858.html
这是一个翻译工具,Python写的,刚学Python,不错的入门。
去这里下这个库:http://www.crummy.com/software/BeautifulSoup/【BeautifulSoup,看了便知】
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 '' word = raw_input() 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 if __name__=="__main__": Translate().Start()
转载于:https://blog.51cto.com/tuoxie174/440285