python实现简易搜索引擎(含代码)

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
简介: python实现简易搜索引擎(含代码)

今天我们使用python来搭建简易的搜索引擎。

搜索引擎的本质其实就是对数据的预处理,分词构建索引和查询。

(这边我们默认所有的数据都是utf-8的数据类型)


我们在一个网站上去获取所有的URL:


def crawl(pages,depth=2):
    for i in range(depth):
        newpages = set()
        for page in pages:
            try:
                c = urllib.request.urlopen(page)
            except:
                print('Invaild page:',page)
                continue
            soup = bs4.BeautifulSoup(c.read())
            links = soup('a')
            for link in links:
                if('href' in dict(link.attrs)):
                    url = urllib.urljoin(page,link['href'])
                    if url.find("'")!=-1:continue
                    url = url.split('#')[0]
                    if url[0:3]=='http':
                        newpages.add(url)
        pages = newpages

通过一个循环抓取当前页面上所有的链接,我们尽可能多的去抓取链接,之所以选择set而不使用list是防止重复的现象,我们可以将爬取的的网站存放到文件或者MySQL或者是MongoDB里。


output = sys.stdout
outputfile = open('lujing.txt', 'w')
sys.stdout = outputfile
list = GetFileList(lujing, [])

将生成的路径文件lujing.txt读取,并按照路径文件对文本处理


# 将生成的路径文件lujing.txt读取,并按照路径文件对文本处理,去标签
for line in open("lujing.txt"):
    print(line)
    # line=line[0:-2]
    line1 = line[0:12]
    line2 = line[13:16]
    line3 = line[17:-1]
    line4 = line[17:-6]
    line = line1 + '\\' + line2 + '\\' + line3
    print(line4)
    path = line
    fb = open(path, "rb")
    data = fb.read()
    bianma = chardet.detect(data)['encoding']  # 获取当前文件的编码方式,并按照此编码类型处理文档
    page = open(line, 'r', encoding=bianma, errors='ignore').read()
    dr = re.compile(r'<[^>]+>', re.S)  # 去HTML标签
    dd = dr.sub('', page)
    print(dd)
    fname = 'TXT' + "\\" + line4 + ".txt"
    # print(fname)
    f = open(fname, "w+", encoding=bianma)  # 将去标签的文件写到文件夹内,并按照原命名以txt文档方式保存
    # fo=open(fname,"w+")
    f.write(dd)



下面我们进行分词索引:

因为大家都比较熟悉sql语句那我在这里就写成MySQL的版本了,如果需要mongodb的可以私信公众号。


import jieba
import chardet
import pymysql
import importlib, sys
importlib.reload(sys)
# 如果使用MongoDB
# from pymongo import MongoClient
# #data processing
# client = MongoClient('localhost',27017)
# apiDB = client['urlDB']    #serverDB_name:test_nodedata
# questionnaires = apiDB['weburl']
# data = list(questionnaires.find())
conn = pymysql .connect(host="localhost",user="root",
                       password="123456",db="suoyin",port=3307)
conn.text_factory = str
c = conn.cursor()
c.execute('drop table doc')
c.execute('create table doc (id int primary key,link text)')
c.execute('drop table word')
c.execute('create table word (term varchar(25) primary key,list text)')
conn.commit()
conn.close()
def Fenci():
    num = 0
    for line in open("url.txt"):
        lujing = line
        print(lujing)
        num += 1
        print(line)
        line = line[17:-5]
        print(line)
        line = 'TXT' + '\\' + line + 'Txt'  # line为文件位置
        print(line)  # 文件名称
        path = line
        fb = open(path, "rb")
        data = fb.read()
        bianma = chardet.detect(data)['encoding']  # 获取文件编码        print(bianma)
        # page = open(line, 'r', encoding=bianma, errors='ignore').read()
        # page1=page.decode('UTF-8')
        if bianma == 'UTF-16':
            data = data.decode('UTF-16')
            data = data.encode('utf-8')
        word = jieba.cut_for_search(data)
        seglist = list(word)
        print(seglist)
        # 创建数据库
        c = conn.cursor()  # 创建游标
        c.execute('insert into doc values(?,?)', (num, lujing))
        # 对每个分出的词语建立词表
        for word in seglist:
            # print(word)
            # 检验看看这个词语是否已存在于数据库
            c.execute('select list from word where term=?', (word,))
            result = c.fetchall()
            # 如果不存在
            if len(result) == 0:
                docliststr = str(num)
                c.execute('insert into word values(?,?)', (word, docliststr))
            # 如果已存在
            else:
                docliststr = result[0][0]  # 得到字符串
                docliststr += ' ' + str(num)
                c.execute('update word set list=? where term=?', (docliststr, word))
        conn.commit()
        conn.close()
Fenci()


最后一步,查询:


import pymsql
import jieba
import math
conn = pymysql .connect(host="localhost",user="root",
                       password="123456",db="suoyin",port=3307)
c = conn.cursor()
c.execute('select count(*) from doc')
N = 1 + c.fetchall()[0][0]  # 文档总数
target = input('请输入搜索词:')
seggen = jieba.cut_for_search(target)
score = {}  # 文档号:匹配度
for word in seggen:
    print('得到查询词:', word)
    # 计算score
    tf = {}  # 文档号:文档数
    c.execute('select list from word where term=?', (word,))
    result = c.fetchall()
    if len(result) > 0:
        doclist = result[0][0]
        doclist = doclist.split(' ')
        # 把字符串转换为元素为int的list
        doclist = [int(x) for x in doclist]
        # 当前word对应的df数
        df = len(set(doclist))
        idf = math.log(N / df)
        print('idf:', idf)
        for num in doclist:
            if num in tf:
                tf[num] = tf[num] + 1
            else:
                tf[num] = 1
        # tf统计结束,现在开始计算score
        for num in tf:
            if num in score:
                # 如果该num文档已经有分数了,则累加
                score[num] = score[num] + tf[num] * idf
            else:
                score[num] = tf[num] * idf
sortedlist = sorted(score.items(), key=lambda d: d[1], reverse=True)
cnt = 0
for num, docscore in sortedlist:
    cnt = cnt + 1
    c.execute('select link from doc where id=?', (num,))
    url = c.fetchall()[0][0]
    print("Result Ranking:", cnt)
    print('url:', url, 'match degree:', docscore)
    if cnt > 20:
        break
if cnt == 0:
    print('No result')


搞定。

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
10天前
|
JavaScript 前端开发 Python
用python执行js代码:PyExecJS库
文章讲述了如何使用PyExecJS库在Python环境中执行JavaScript代码,并提供了安装指南和示例代码。
54 1
用python执行js代码:PyExecJS库
|
7天前
|
Python
以下是一些常用的图表类型及其Python代码示例,使用Matplotlib和Seaborn库。
以下是一些常用的图表类型及其Python代码示例,使用Matplotlib和Seaborn库。
|
10天前
|
Python
turtle库的几个案例进阶,代码可直接运行(python经典编程案例)
该文章展示了使用Python的turtle库进行绘图的进阶案例,包括绘制彩色圆形和复杂图案的代码示例。
51 6
turtle库的几个案例进阶,代码可直接运行(python经典编程案例)
|
2天前
|
数据安全/隐私保护 Python
探索Python中的装饰器:简化代码,提升效率
【9月更文挑战第32天】在Python编程世界中,装饰器是一个强大的工具,它允许我们在不改变函数源代码的情况下增加函数的功能。本文将通过直观的例子和代码片段,引导你理解装饰器的概念、使用方法及其背后的魔法,旨在帮助你写出更加优雅且高效的代码。
|
1天前
|
大数据 Python
Python 高级编程:深入探索高级代码实践
本文深入探讨了Python的四大高级特性:装饰器、生成器、上下文管理器及并发与并行编程。通过装饰器,我们能够在不改动原函数的基础上增添功能;生成器允许按需生成值,优化处理大数据;上下文管理器确保资源被妥善管理和释放;多线程等技术则助力高效完成并发任务。本文通过具体代码实例详细解析这些特性的应用方法,帮助读者提升Python编程水平。
18 5
|
6天前
|
Python
? Python 装饰器入门:让代码更灵活和可维护
? Python 装饰器入门:让代码更灵活和可维护
12 4
|
6天前
|
缓存 测试技术 Python
探索Python中的装饰器:简化代码,提高可读性
【9月更文挑战第28天】在Python编程中,装饰器是一个强大的工具,它允许我们在不修改原有函数代码的情况下增加额外的功能。本文将深入探讨装饰器的概念、使用方法及其在实际项目中的应用,帮助读者理解并运用装饰器来优化和提升代码的效率与可读性。通过具体示例,我们将展示如何创建自定义装饰器以及如何利用它们简化日常的编程任务。
11 3
|
5天前
|
机器学习/深度学习 数据格式 Python
将特征向量转化为Python代码
将特征向量转化为Python代码
12 1
|
10天前
|
Python
turtle库的几个简单案例,代码可直接运行(python经典编程案例)
该文章提供了多个使用Python的turtle库绘制不同图形的简单示例代码,如画三角形、正方形、多边形等,展示了如何通过turtle进行基本的绘图操作。
17 5
|
10天前
|
NoSQL MongoDB 数据库
python3操作MongoDB的crud以及聚合案例,代码可直接运行(python经典编程案例)
这篇文章提供了使用Python操作MongoDB数据库进行CRUD(创建、读取、更新、删除)操作的详细代码示例,以及如何执行聚合查询的案例。
22 6
下一篇
无影云桌面