python在线抓取百度词典的翻译结果翻译单词,python抓取,这段代码通过抓取百度词典
python在线抓取百度词典的翻译结果翻译单词,python抓取,这段代码通过抓取百度词典
这段代码通过抓取百度词典的翻译结果达到翻译单词的目的
这个小工具使用Python语言编写完成,其中使用到这些类库(urllib,BeautifulSoup),前者主要负责网络通讯方面,后者负责HTML的解析。这也是Python语言生态圈的强大之处,写个这样的小工具,毫不费力。在线翻译的原理:首先根据用户输入的单词提交给百度词典,其次读取百度词典返回的数据并解析,最后将处理过的数据显示给用户。以下是该工具的具体代码(Translate.py)```pythonimport urllibimport codecsfrom BeautifulSoup import BeautifulSoupfrom sys import argvimport 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通过datetime模块计算各种时间间隔,pythondatetime,p
- python通过正则表达式分析网页中的图片并进行替换,
- python获得两个数组的交集、并集、差集,python交集,py
- python去除列表里的重复元素的集中方法汇总,python汇总
- python多线程有几种实现方法,python多线程,python多线程有
- python编写简单抽奖系统,python编写抽奖,#!/usr/bin/e
- python通过reportlab实现图片转换pdf,,Reportlab是用p
- 用Python实现一个简单的算术游戏,python实现算术,用Py
- python从网络端口读取文本数据,,# To test it
- python常用字典操作范例,python字典范例,# experiment
评论关闭