全系列目录:

  • 【原创】shadowebdict开发日记:基于linux的简明英汉字典(一)
  • 【原创】shadowebdict开发日记:基于linux的简明英汉字典(二)
  • 【原创】shadowebdict开发日记:基于linux的简明英汉字典(三)
  • 【原创】shadowebdict开发日记:基于linux的简明英汉字典(四)
  • 项目的github地址

承接上文。

现在来进行response模块的开发。

这一模块所完成的任务是,如果本地的词库中没有用户需要查询的词汇,那么就去网络上寻找到相应的词条作为结果返回,并存入本地数据库。

我选择的网上的源是iciba,理由很简单,不需要复杂的cookie管理,所查词汇的内容基本集成在返回的html源文件中。

值得注意的是,如果请求过于频繁,那么会被iciba ban掉,所以如果要利用这段代码爬iciba的词库,请自行加个sleep。不过好像我代码中也有,注意改下便是。

该模块的逻辑为:

0、提供一个接口给其他模块调用,输入为待查词汇。

1、构造url请求,获得返回的数据。

2、根据数据的格式,解析返回的数据并获取相应词条的内容

3、按照约定的格式返回相应词条的内容给调用其的其他模块

具体的做法参考源代码

# -*- coding:utf-8 -*-
__author__ = 'wmydx'import urllib
import re
import urllib2
import timeclass GetResponse:def __init__(self):self.url = 'http://www.iciba.com/'self.isEng = re.compile(r'(([a-zA-Z]*)(\s*))*$')self.group_pos = re.compile(r'<div class="group_pos">(.*?)</div>', re.DOTALL)self.net_paraphrase = re.compile(r'<div class="net_paraphrase">(.*?)</div>', re.DOTALL)self.sentence = re.compile(r'<dl class="vDef_list">(.*?)</dl>', re.DOTALL)def process_input(self, word):word = word.strip()word = word.replace(' ', '_')return worddef get_data_from_web(self, word):headers = {'Referer': 'http://www.iciba.com/', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) \AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36'}request = urllib2.Request(self.url + word, headers=headers)while True:try:f = urllib2.urlopen(request).read()breakexcept:passreturn fdef get_eng_from_chinese(self, word):word = self.process_input(word)word = urllib.quote(word)data = self.get_data_from_web(word)label_lst = re.compile(r'<span class="label_list">(.*?)</span>', re.DOTALL)label_itm = re.compile(r'<label>(?P<item>.*?)</a>(.*?)</label>', re.DOTALL)first = label_lst.search(data)data = data[first.start():first.end()]start_itm = 0res = []while 1:second = label_itm.search(data, start_itm)if not second:breakword = self.get_sentence_from_dt(data[second.start('item'):second.end('item')])res.append(word)start_itm = second.end()return resdef get_dict_data(self, word):englst = []res = []match = self.isEng.match(word)if not match:englst = self.get_eng_from_chinese(word)else:englst.append(word)for item in englst:word = self.process_input(item)data = self.get_data_from_web(word)if data.find('对不起,没有找到') != -1:res.append(-1)else:tmp_dict = self.analysis_eng_data(data)tmp_dict['word'] = wordtmp_dict['times'] = 1res.append(tmp_dict)return resdef analysis_eng_data(self, data):res = {}explain = self.group_pos.search(data)if explain:explain = data[explain.start():explain.end()]res['explain'] = self.generate_explain(explain)else:res['explain'] = -1net_explain = self.net_paraphrase.search(data)if net_explain:net_explain = data[net_explain.start():net_explain.end()]res['net_explain'] = self.generate_net_explain(net_explain)else:res['net_explain'] = -1sentence_start = 0sentence_end = len(data)sentence_lst = []while sentence_start < sentence_end:sentence = self.sentence.search(data, sentence_start)if sentence:sentence_str = data[sentence.start():sentence.end()]else:breaksentence_lst.append(self.generate_sentence(sentence_str))sentence_start = sentence.end()res['sentence'] = "\n\n".join(sentence_lst)return resdef generate_explain(self, target):start_word = 0end_word = len(target)meta_word = re.compile(r'<strong class="fl">(?P<meta_word>.*?)</strong>', re.DOTALL)label_lst = re.compile(r'<span class="label_list">(.*?)</span>', re.DOTALL)label_itm = re.compile(r'<label>(?P<item>.*?)</label>', re.DOTALL)res = ''while start_word < end_word:first = meta_word.search(target, start_word)if first:word_type = target[first.start('meta_word'):first.end('meta_word')]else:breakres += word_type + ' 'second = label_lst.search(target, first.end('meta_word'))start_label = second.start()end_label = second.end()while start_label < end_label:third = label_itm.search(target, start_label)if third:res += target[third.start('item'):third.end('item')]start_label = third.end()else:breakres += '\n'start_word = end_labelreturn resdef generate_net_explain(self, target):start_itm = 0end_itm = len(target)li_item = re.compile(r'<li>(?P<item>.*?)</li>', re.DOTALL)res = '网络释义: 'while 1:first = li_item.search(target, start_itm)if first:res += target[first.start('item'):first.end('item')]else:breakstart_itm = first.end()return resdef generate_sentence(self, target):res = ''english = re.compile(r'<dt>(?P<eng>.*?)</dt>', re.DOTALL)chinese = re.compile(r'<dd>(?P<chn>.*?)</dd>', re.DOTALL)first = english.search(target)second = chinese.search(target)res += self.get_sentence_from_dt(target[first.start('eng'):first.end('eng')]) + '\n'res += target[second.start('chn'):second.end('chn')]return resdef get_sentence_from_dt(self, target):res = ''length = len(target)index = 0while index < length:if target[index] == '<':while target[index] != '>':index += 1else:res += target[index]index += 1return resif __name__ == '__main__':p = GetResponse()test = ['hello', 'computer', 'nothing', 'bad guy', 'someday']for item in test:res = p.get_dict_data(item)for key in res:for (k, v) in key.items():print "dict[%s]=" % k, vprinttime.sleep(3)

转载于:https://www.cnblogs.com/shadowmydx/p/4335901.html

【原创】shadowebdict开发日记:基于linux的简明英汉字典(三)相关推荐

  1. 基于linux的在线英汉词典(带源码)

    源码下载: 基于Linux的在线英汉词典-网络基础文档类资源-CSDN文库https://download.csdn.net/download/qq_63626307/86744311?spm=100 ...

  2. python英汉字典_Python基于有道实现英汉字典功能

    Python基于有道实现英汉字典功能 本文实例讲述了Python基于有道实现英汉字典功能的方法.分享给大家供大家参考.具体如下: import re,urllib aa="http://di ...

  3. python有道字典_Python基于有道实现英汉字典功能

    本文实例讲述了Python基于有道实现英汉字典功能的方法.分享给大家供大家参考.具体如下: import re,urllib aa="http://dict.youdao.com/searc ...

  4. python制作英汉词典_Python基于有道实现英汉字典功能

    本文实例讲述了Python基于有道实现英汉字典功能的方法.分享给大家供大家参考.具体如下: import re,urllib aa="http://dict.youdao.com/searc ...

  5. python英汉字典,Python基于有道实现英汉字典功能,python英汉字典

    Python基于有道实现英汉字典功能,python英汉字典 本文实例讲述了Python基于有道实现英汉字典功能的方法.分享给大家供大家参考.具体如下: import re,urllib aa=&quo ...

  6. Android 是Google开发的基于Linux平台的开源手机操作系统

    Android 是Google开发的基于Linux平台的开源手机操作系统(在华注册商标名为"安致").它摩托罗拉的首款Android手机CLIQ包括操作系统.用户界面和应用程序 - ...

  7. 基于linux的应用开发视频教程,基于LINUX+ARM的视频系统的应用和开发

    摘要: 随着经济的发展,人民生活水平的提高,嵌入式智能产品越来越多的进入到到我们生活领域,这些产品不仅给我们带来方便,同时也在改变着我们的生活,并且嵌入式产品界面和视频的开发也越来越受到关注,成为研究 ...

  8. spring boot 与 iview 前后端分离架构之开发环境基于docker的部署的实现(三十六)

    spring boot 与 iview 前后端分离架构之开发环境基于docker的后端的部署的实现(三十六) 公众号 基于docker的后端的部署 安装mysql数据库 创建数据库 安装redis 安 ...

  9. linux英汉字典代码,Ubuntu安装英汉词典(词库)详细步骤

    Ubuntu安装英汉词典(词库)详细步骤 发布时间:2013-05-26 11:26:08   作者:佚名   我要评论 linux并不缺少词典软件.但是缺少词库.所有的词典软件都需要,自己下载安装词 ...

最新文章

  1. android读取excel数据库,Android 读取Excel数据并保存在本地数据库
  2. Huber loss--转
  3. 库 python_20个必不可少的Python库也是基本的第三方库
  4. vue history模式Nginx配置
  5. php 转换数组为小写,PHP如何将数组键转换为小写?
  6. 编辑距离 dp_使用动态编程(DP)编辑距离
  7. JS实现查找数组中对象的属性值是否存在
  8. Ambari——大数据平台的搭建利器之进阶篇[配置spark]
  9. 联想笔记本大写提示软件_联想威6 2021款怎么样?值得买吗?下面几点或许可以帮到您...
  10. TH75 V2 双模蓝牙5.2热插拔PCB
  11. 调节e18-d80nk的测量距离_没有倒车影像,用这个方法判断后方墙壁距离,这个距离感这样练习...
  12. 红孩儿编辑器的开发 1 字体库的生成过程
  13. EMNIST: an extension of MNIST to handwritten letters(数据集简介)
  14. 擦地机器人排行榜_十大扫地机器人品牌排行榜扫地机器人哪个牌子好
  15. 雅虎的站长天下要关门了,哎,真是悲哀
  16. 页面生命周期:DOMContentLoaded,load,beforeunload,unload
  17. excel计算标准分
  18. 【bug】missing required field “selector“ in io.k8s.api.apps.v1.DeploymentSpec;
  19. IC设计前后端常用的英文术语
  20. spring data jpa使用详解

热门文章

  1. mysql 索引空间大小_查看数据库表中容量大小,表有多少记录,占多少空间以及索引的大小,以及未使用空间...
  2. 深度学习图像融合_基于深度学习的图像超分辨率最新进展与趋势【附PDF】
  3. 基于Java+SpringBoot+vue+element实现扶贫助农政策平台系统
  4. 林辉高考机器人_机器人2019年参加高考 力争考上一本
  5. python mysql dbutils_python操作mysql数据库增删改查的dbutils实例
  6. android webview简单使用,android WebView 简单使用Demo
  7. python读取csv画图datetime_python – CSV数据(Timestamp和事件)的时间表绘图:x-label常量...
  8. 存储器块清零c语言版,存储器块清零实验报告
  9. Spring Boot MyBatis
  10. Jsoup根据URL加载一个Document