写点什么

基于 Serverless 快速实现简单版查询工具

  • 2020-06-28
  • 本文字数:7777 字

    阅读完需:约 26 分钟

基于Serverless快速实现简单版查询工具

朋友的单位有一个小型的图书室,图书室中摆放了很多的书,每本书都被编号放在对应的区域,为了让大家更快、更容易找到这些书,他联系我,让我帮他弄一个图书查询系统,通过用户输入能模糊匹配到对应的结果,并且提供书籍对应的地点。

功能设计

  • 让朋友把书籍整理并存储到一个 Excel 表格中;

  • 将 Excel 表放到对象存储中,云函数读取这个文件并解析;

  • 根据词语的相似寻找相似的图书;

  • 前端页面通过 MUI 制作,放在对象存储中,并且使用对象存储的 Website 功能;

整体实现

数据形态

Excel 样式主要包括书名和编号,同时下面包括分类的 tab:


基于函数的搜索功能

核心代码实现:


import jiebaimport openpyxlfrom gensim import corpora, models, similaritiesfrom collections import defaultdictimport urllib.request
with open("/tmp/book.xlsx", "wb") as f: f.write( urllib.request.urlopen("https://********").read() )

top_str = "abcdefghijklmn"book_dict = {}book_list = []wb = openpyxl.load_workbook('/tmp/book.xlsx')sheets = wb.sheetnamesfor eve_sheet in sheets: print(eve_sheet) sheet = wb.get_sheet_by_name(eve_sheet) this_book_name_index = None this_book_number_index = None for eve_header in top_str: if sheet[eve_header][0].value == "书名": this_book_name_index = eve_header if sheet[eve_header][0].value == "编号": this_book_number_index = eve_header print(this_book_name_index, this_book_number_index) if this_book_name_index and this_book_number_index: this_book_list_len = len(sheet[this_book_name_index]) for i in range(1, this_book_list_len): add_key = "%s_%s_%s" % ( sheet[this_book_name_index][i].value, eve_sheet, sheet[this_book_number_index][i].value) add_value = { "category": eve_sheet, "name": sheet[this_book_name_index][i].value, "number": sheet[this_book_number_index][i].value } book_dict[add_key] = add_value book_list.append(add_key)

def getBookList(book, book_list): documents = [] for eve_sentence in book_list: tempData = " ".join(jieba.cut(eve_sentence)) documents.append(tempData) texts = [[word for word in document.split()] for document in documents] frequency = defaultdict(int) for text in texts: for word in text: frequency[word] += 1 dictionary = corpora.Dictionary(texts) new_xs = dictionary.doc2bow(jieba.cut(book)) corpus = [dictionary.doc2bow(text) for text in texts] tfidf = models.TfidfModel(corpus) featurenum = len(dictionary.token2id.keys()) sim = similarities.SparseMatrixSimilarity( tfidf[corpus], num_features=featurenum )[tfidf[new_xs]] book_result_list = [(sim[i], book_list[i]) for i in range(0, len(book_list))] book_result_list.sort(key=lambda x: x[0], reverse=True) result = [] for eve in book_result_list: if eve[0] >= 0.25: result.append(eve) return result

def main_handler(event, context): try: print(event) name = event["body"] print(name) base_html = '''<div class='mui-card'><div class='mui-card-header'>{{book_name}}</div><div class='mui-card-content'><div class='mui-card-content-inner'>分类:{{book_category}}<br>编号:{{book_number}}</div></div></div>''' result_str = "" for eve_book in getBookList(name, book_list): book_infor = book_dict[eve_book[1]] result_str = result_str + base_html.replace("{{book_name}}", book_infor['name']) \ .replace("{{book_category}}", book_infor['category']) \ .replace("{{book_number}}", book_infor['number'] if book_infor['number'] else "") if result_str: return result_str except Exception as e: print(e) return '''<div class='mui-card' style='margin-top: 25px'><div class='mui-card-content'><div class='mui-card-content-inner'>未找到图书信息,请您重新搜索。</div></div></div>'''
复制代码


同时配置 APIGW:


功能页面

<!DOCTYPE html><html><head>    <meta charset="utf-8">    <title>图书检索系统</title>    <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">    <meta name="apple-mobile-web-app-capable" content="yes">    <meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="stylesheet" href="https://others-1256773370.cos.ap-chengdu.myqcloud.com/booksearch/css/mui.min.css"> <style> html, body { background-color: #efeff4; } </style> <script> function getResult() { var UTFTranslate = { Change: function (pValue) { return pValue.replace(/[^\u0000-\u00FF]/g, function ($0) { return escape($0).replace(/(%u)(\w{4})/gi, "&#x$2;") }); }, ReChange: function (pValue) { return unescape(pValue.replace(/&#x/g, '%u').replace(/\\u/g, '%u').replace(/;/g, '')); } };
var xmlhttp; if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码 xmlhttp = new XMLHttpRequest(); } else { // IE6, IE5 浏览器执行代码 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200 && xmlhttp.responseText) { document.getElementById("result").innerHTML = UTFTranslate.ReChange(xmlhttp.responseText).slice(1, -1).replace("\"",'"'); } } xmlhttp.open("POST", "https://********", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send(document.getElementById("book").value); } </script></head><body><div class="mui-content" style="margin-top: 50px"> <h3 style="text-align: center">图书检索系统</h3> <div class="mui-content-padded" style="margin: 10px; margin-top: 20px"> <div class="mui-input-row mui-search"> <input type="search" class="mui-input-clear" placeholder="请输入图书名" id="book"> </div> <div class="mui-button-row"> <button type="button" class="mui-btn mui-btn-numbox-plus" style="width: 100%" onclick="getResult()">检索 </button>&nbsp;&nbsp; </div> </div> <div id="result"> <div class="mui-card" style="margin-top: 25px"> <div class="mui-card-content"> <div class="mui-card-content-inner"> 可以在搜索框内输入书籍的全称,或者书籍的简称,系统支持智能检索功能。 </div> </div> </div> </div></div><script src="https://others-1256773370.cos.ap-chengdu.myqcloud.com/booksearch/js/mui.min.js"></script></body></html>
复制代码

效果展示

为了便于朋友使用,我将这个页面用 Webview 封装成一个 APP,整体效果如下:


总结

这是一个低频使用的 APP,如果是构建在传统服务器上,不是一个明智的选择,而云函数的按量付费,对象存储与 APIGW 的融合,完美解决了资源浪费的问题,同时借用云函数的 APIGW 触发器,可以很简单轻松的替代传统的 Web 框架和部分服务器软件的安装和使用、维护等。这个例子非常小,但却是一个有趣的小工具,除了图书查询之外,我们还可以继续拓展构建其它系统,例如成绩查询等。


2020-06-28 16:341602

评论

发布
暂无评论
发现更多内容

OpenAI的Sora亮相:AI视频生成的新用场

算AI

人工智能 创业 创新 sora

开发竞猜比分与专家分析功能:如何为体育直播平台注入新活力

软件开发-梦幻运营部

QCN9274 QCN6274 IPQ9574|What Does Wi-Fi 7 Actually Bring?

wallyslilly

qcn9274 qcn6274 ipq9574

听 GPT 讲 client-go 源代码 (10)

fliter

AI 优化学习路径:个性化推荐与辅助学习

测吧(北京)科技有限公司

测试

2023 re:Invent 用 PartyRock 10 分钟构建你的 AI 应用

亚马逊云科技 (Amazon Web Services)

亚马逊云科技 生成式人工智能 Amazon CodeWhisperer Amazon Bedrock Amazon Q

听 GPT 讲 client-go 源代码 (9)

fliter

解锁Mysql中的JSON数据类型,怎一个爽字了得

不在线第一只蜗牛

json MySQL 数据库 开发语言

自动化测试创新:AI 驱动的测试策略变革

测吧(北京)科技有限公司

测试

k8s-权限管理

EquatorCoco

Kubernetes 云原生 k8s

今日必读的9篇大模型论文

学术头条

人工智能 论文 大模型

揭秘 LLMs 时代向量数据库的 3 大实用场景

Zilliz

Milvus 向量数据库 LLM zillizcloud rag

CORS就是跨域吗?

EquatorCoco

CORS web开发 跨域

马斯克称首位受试者可凭思维操控鼠标;字节低调推出视频模型丨 RTE 开发者日报 Vol.148

声网

OpenTiny Vue 组件库适配微前端可能遇到的4个问题

OpenTiny社区

开源 Vue 前端 微前端 组件库

测试流程智能化:AI 技术赋能测试领域

测吧(北京)科技有限公司

测试

你好,iLogtail 2.0!

阿里巴巴云原生

阿里云 云原生 iLogtail

京东商品优惠券数据采集

tbapi

京东 京东API接口 京东商品优惠券数据 京东商品详情数据

接手外包团队开发的微服务项目,人麻了!

伤感汤姆布利柏

大语言模型支持:开发个性化 AI 应用

测吧(北京)科技有限公司

测试

区块链游戏解说:什么是 Planet IX

Footprint Analytics

web3

EMQX Enterprise 5.4 发布:OpenTelemetry 分布式追踪、OCPP 网关、Confluent 集成支持

EMQ映云科技

mqtt emqx mqtt broker

面试官:如何实现多级缓存?

不在线第一只蜗牛

缓存 程序员 面试

盘一盘制造业最受欢迎的9个IT岗位

伤感汤姆布利柏

拼多多商品优惠券数据采集

tbapi

拼多多 拼多多商品详情接口 拼多多商品数据采集

inBuilder低代码平台新特性推荐-第十六期

inBuilder低代码平台

开源 低代码

龙蜥系统运维联盟:Kindling-OriginX 如何集成 DeepFlow 的数据增强网络故障的解释力

OpenAnolis小助手

deepflow 开源 系统运维 ebpf 龙蜥社区

【论文解读】transformer小目标检测综述

合合技术团队

目标检测 Transformer 深度学习、

企业定制化 AI 解决方案:满足企业需求的智能服务

测吧(北京)科技有限公司

测试

基于Serverless快速实现简单版查询工具_服务革新_刘宇_InfoQ精选文章