python在線抓取百度詞典的翻譯結果翻譯單詞
這段代碼通過抓取百度詞典的翻譯結果達到翻譯單詞的目的
這個小工具使用Python語言編寫完成,其中使用到這 些類庫(urllib,BeautifulSoup ),前者主要負責網絡通訊方面,后者負責HTML的解析。這也是Python語言生態圈的強大之處,寫個這樣的小工具,毫不費力。
在線翻譯的原理:首先根據用戶輸入的單詞提交給百度詞典 ,其次讀取百度詞典返回的數據并解析,最后將處理過的數據顯示給用戶。以下是該工具的具體代碼(Translate.py)
import urllib import codecs from BeautifulSoup import BeautifulSoup from sys import argv import re,timeclass 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 sharejs.com
if name=="main": Translate().Start()</pre>
本文由用戶 pycct 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!