搜索引擎主题模型优化(我们能不能利用爬虫,自己制作一个简单的搜索引擎呢?)
优采云 发布时间: 2022-01-20 19:16搜索引擎主题模型优化(我们能不能利用爬虫,自己制作一个简单的搜索引擎呢?)
通常我们要搜索东西的时候,经常会用到百度百科,比如搜索“上海”,会出现如下页面:
那么,我们可以使用爬虫自己做一个简单的搜索引擎吗?
为什么不?!我们自己做一个简单的搜索引擎,展示输入词条的介绍部分,既可以减少工作量,又可以展示搜索引擎的基本原理。
以下是作者制作的一个简单的搜索引擎。实现的功能是:读取输入词条,输出百度百科词条的介绍部分。
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 18 15:58:13 2017
@author: JClian
"""
import re
import bs4
import urllib.request
from bs4 import BeautifulSoup
import urllib.parse
import sys
search_item = input("Enter what you want(Enter 'out' to exit):")
while search_item != 'out':
if search_item == 'out':
exit(0)
print("please wait...")
try:
url = 'https://baike.baidu.com/item/'+urllib.parse.quote(search_item)
html = urllib.request.urlopen(url)
content = html.read().decode('utf-8')
html.close()
soup = BeautifulSoup(content, "lxml")
text = soup.find('div', class_="lemma-summary").children
print("search result:")
for x in text:
word = re.sub(re.compile(r""),'',str(x))
words = re.sub(re.compile(r"\[(.+?)\]"),'',word)
print(words,'\n')
except AttributeError:
print("Failed!Please enter more in details!")
search_item = input("Enter what you want(Enter 'out' to exit):")
其中search_item为输入入口,进入while循环一直搜索,输入'out'时退出。text是词条的百度百科介绍的网页形式,里面的文本是通过正则表达式提取出来的(当然提取出来的文本形式还是需要美化的~~)。如果百度百科中没有该条目,则输出失败信息,并提示测试指定条目后再输入。这样,对于百度百科中的词条,我们的搜索引擎也有响应的简要介绍部分。
接下来是测试时间(在 Jupyter Notebook 上测试):
测试效果还是不错的,真的很简单好用,你也试试吧?
本次分享如有不足之处,欢迎批评指正。欢迎交流^O^