python 百度词典_python在线抓取百度词典的翻译结果翻译单词
這段代碼通過抓取百度詞典的翻譯結果達到翻譯單詞的目的
這個小工具使用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 sharejs.com
if __name__=="__main__":
Translate().Start()
總結
以上是生活随笔為你收集整理的python 百度词典_python在线抓取百度词典的翻译结果翻译单词的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 姓许的男孩名字?
- 下一篇: python计算和差积商_Python与