python怎样写一个索引排序功能?
Admin 2021-05-18 群英技术资讯 962 次浏览
这篇文章主要给大家分享如何Python实现索引排序功能,小编觉得是比较有意思的,因此与大家分享一下,下面我们就一起来看看具体的实现吧。
代码如下图:
import requests import re def News_Spider():#定义一个爬虫 url = 'https://news.sina.com.cn/'#url地址,新浪新闻 headers = {#请求头 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36' } response = requests.get(url,headers,verify=False)#针对https,采用verify=False response.encoding='utf-8'#编码方式 html = response.text#获取页面源代码 #print(html)#打印源代码 reg = 'target="_blank">(.*?)</a>'#设置规则 content = re.findall(reg,html)#从页面源代码中筛选 ls = []#定义一个空列表 for c in content: if '<' in c: continue else: if len(c) > 6 and '客户端' not in c: #print(c) ls.append(c) else: continue docu_set = {}#定义一个字典 for l in range(len(ls)): docu_set['d{}'.format(l+1)] = ls[l]#格式化方法,从1开始 return docu_set def change_set(): all_words = []#定义一个空列表用于存储 docu_set = News_Spider() for i in docu_set.values(): cut = i.split()#分词 all_words.extend(cut)#添加分词 set_all_words = set(all_words) return set_all_words #print(set_all_words) def reverse_index(): invert_index = dict()#定义空字典 set_all_words = change_set()#将返回值传递给变量 docu_set = News_Spider() for b in set_all_words: temp = [] for k in docu_set.keys(): field = docu_set[k] split_field = field.split() if b in split_field: temp.append(k) invert_index[b] = temp print(invert_index) return invert_index def Select(): docu_set = News_Spider() invert_index = reverse_index() news = [] # for i in invert_index: # print(invert_index[i]) while True: Find = str(input('请输入查找内容:')) if Find == '不查了': break for Contetnt in invert_index:#循环每一个键 if Find in Contetnt:#如果输入在键的字符串中 Result = invert_index[Contetnt]#循环出字典中每一个对应的值 #print(Result) for r in Result:#循环每一个值 if r in docu_set.keys():#如果值在字典中 news.append(docu_set[r])#列表增加字典docu_set的值 print(docu_set[r])#打印输出字典的值 else: continue else: if Find not in Contetnt: news.append('很抱歉,没有找到更多内容!!') #news = set(news) for n in news: if '很抱歉' in n: print(n) break else: print(n) def main_function():#定义一个主方法 News_Spider() change_set() reverse_index() Select() if __name__ == '__main__':#程序入口 main_function()
运行结果如下图:
关于代码的解释,我写在注释中了。
以上就是关于Python实现索引排序功能的介绍,此外还介绍了搜索功能的实现,需要的朋友可以参考上述代码,想要了解更多Python相关内容,大家可以关注其他文章。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
那么如何使我们输入的文本在输出我们想要的对齐方式呢?其实用我们的format就可以解决,我们一起来看看如何操作吧。
这篇文章主要介绍了Python小技巧练习分享,文章基于python的相关内容展开详细的python小技巧内容,具有一定的参考价值,需要的小伙伴可以参考一下
三元表达式是编程中比较常用的,这篇文章就主要给大家分享python的三元表达式怎样用的操作,对新手学习python的三元表达式具有一定的借鉴价值,感兴趣的朋友可以参考一下,希望大家阅读完这篇文章能有所收获,下面我们一起来学习一下吧。
在编写代码的时候,经常会出现写的代码存在一些问题,但是比较难以发现具体存在的问题在哪里,需要将带代码恢复到指定的版本,下面这篇文章主要给大家介绍了关于pycharm中代码回滚到指定版本的两种实现方法,需要的朋友可以参考下
这篇文章主要介绍了详解Python+opencv裁剪/截取图片的几种方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008