如何使用Trie树,设计实践Google一样的输入提示功能

来源 | 搜索技术
责编 | 小白

Google和百度都支持输入提示功能,辅助你快速准确的输入想要的内容。

如下:输入“五一”,会提示“五一劳动节”等。

那如何实现谷歌这样的输入提示功能呢?

分析下输入提示的功能需求

当输入前面的词A,希望提示出前缀为A的所有高相关性的词。这个特性属于前缀匹配,trie树被称为前缀树,是一种搜索排序树,很适合用作输入提示的实践。

下面以python3为例,使用Trie树,构建输入提示服务。

# Python3 program to demonstrate auto-complete  # feature using Trie data structure. # Note: This is a basic implementation of Trie # and not the most optimized one. class TrieNode():     def __init__(self):# Initialising one node for trie         self.children = {}         self.last = False
class Trie():     def __init__(self):# Initialising the trie structure.         self.root = TrieNode()         self.word_list = []def formTrie(self, keys):# Forms a trie structure with the given set of strings         # if it does not exists already else it merges the key         # into it by extending the structure as required         for key in keys:             self.insert(key) # inserting one key to the trie.def insert(self, key):# Inserts a key into trie if it does not exist already.         # And if the key is a prefix of the trie node, just          # marks it as leaf node.         node = self.rootfor a in list(key):             if not node.children.get(a):                 node.children[a] = TrieNode()node = node.children[a]node.last = Truedef search(self, key):# Searches the given key in trie for a full match         # and returns True on success else returns False.         node = self.root         found = Truefor a in list(key):             if not node.children.get(a):                 found = False                breaknode = node.children[a]return node and node.last and founddef suggestionsRec(self, node, word):# Method to recursively traverse the trie         # and return a whole word.          if node.last:             self.word_list.append(word)for a,n in node.children.items():             self.suggestionsRec(n, word + a)def printAutoSuggestions(self, key):# Returns all the words in the trie whose common         # prefix is the given key thus listing out all          # the suggestions for autocomplete.         node = self.root         not_found = False        temp_word = ''for a in list(key):             if not node.children.get(a):                 not_found = True                breaktemp_word += a             node = node.children[a]if not_found:             return 0        elif node.last and not node.children:             return -1self.suggestionsRec(node, temp_word)for s in self.word_list:             print(s)         return 1
# Driver Codekeys = ["五一", "五一劳动节", "五一放假安排", "五一劳动节图片", "五一劳动节图片 2020", "五一劳动节快乐", "五一晚会", "五一假期", "五一快乐","五一节快乐", "五花肉",        "五行", "五行相生"] # keys to form the trie structure.key = "五一" # key for autocomplete suggestions.status = ["Not found", "Found"]
# creating trie objectt = Trie()
# creating the trie structure with the# given set of strings.t.formTrie(keys)
# autocompleting the given key using# our trie structure.comp = t.printAutoSuggestions(key)
if comp == -1:    print("No other strings found with this prefix\n")elif comp == 0:    print("No string found with this prefix\n")
# This code is contributed by amurdia

输入:五一,输入提示结果如下:

结果都实现了,但我们实现后的输入提示顺序跟Google有点不一样,那怎么办呢?

一般构建输入提示的数据源都是用户输入的query词的日志数据,并且会统计每个输入词的次数,以便按照输入词的热度给用户提示。

现在我们把日志词库加上次数,来模拟Google的输入效果。

日志库的查询词及个数示例如下:

五一劳动节 10五一劳动节图片 9五一假期 8五一劳动节快乐 7五一放假安排 6五一晚会 5五一 4五一快乐 3五一劳动节图片2020 2五一快乐 1

把输入提示的代码调整下,支持查询词次数的支持:

# Python3 program to demonstrate auto-complete  # feature using Trie data structure. # Note: This is a basic implementation of Trie # and not the most optimized one. import operatorclass TrieNode():     def __init__(self):                   # Initialising one node for trie         self.children = {}         self.last = False  class Trie():     def __init__(self):                   # Initialising the trie structure.         self.root = TrieNode()         #self.word_list = []         self.word_list = {}      def formTrie(self, keys):                   # Forms a trie structure with the given set of strings         # if it does not exists already else it merges the key         # into it by extending the structure as required         for key in keys:             self.insert(key) # inserting one key to the trie.       def insert(self, key):                   # Inserts a key into trie if it does not exist already.         # And if the key is a prefix of the trie node, just          # marks it as leaf node.         node = self.root           for a in list(key):             if not node.children.get(a):                 node.children[a] = TrieNode()               node = node.children[a]           node.last = True      def search(self, key):                   # Searches the given key in trie for a full match         # and returns True on success else returns False.         node = self.root         found = True          for a in list(key):             if not node.children.get(a):                 found = False                break              node = node.children[a]           return node and node.last and found       def suggestionsRec(self, node, word):                   # Method to recursively traverse the trie         # and return a whole word.          if node.last:             #self.word_list.append(word)            ll = word.split(',')            if(len(ll) >= 2):                self.word_list[ll[0]] = int(ll[1])            else:                self.word_list[ll[0]] = 0          for a,n in node.children.items():             self.suggestionsRec(n, word + a)       def printAutoSuggestions(self, key):                   # Returns all the words in the trie whose common         # prefix is the given key thus listing out all          # the suggestions for autocomplete.         node = self.root         not_found = False        temp_word = ''           for a in list(key):             if not node.children.get(a):                 not_found = True                break              temp_word += a             node = node.children[a]           if not_found:             return 0        elif node.last and not node.children:             return -1          self.suggestionsRec(node, temp_word)           #sort        sorted_d = dict(sorted(self.word_list.items(), key=operator.itemgetter(1),reverse=True))        for s in sorted_d.keys():             print(s)         return 1
# Driver Codekeys = ["五一,4", "五一劳动节,10", "五一放假安排,6", "五一劳动节图片,9", "五一劳动节图片 2020,2", "五一劳动节快乐,7", "五一晚会,5", "五一假期,8", "五一快乐,3","五一节快乐,1", "五花肉,0",        "五行,0", "五行相生,0"] # keys to form the trie structure.key = "五一" # key for autocomplete suggestions.status = ["Not found", "Found"]
# creating trie objectt = Trie()
# creating the trie structure with the# given set of strings.t.formTrie(keys)
# autocompleting the given key using# our trie structure.comp = t.printAutoSuggestions(key)
if comp == -1:    print("No other strings found with this prefix\n")elif comp == 0:    print("No string found with this prefix\n")
# This code is contributed by amurdia

输出结果跟Google一模一样:

总结:

以上是使用Trie树,实践Google输入提示的功能。除了Trie树实践,我们还有其他办法么,搜索中有没有其他的索引能很好实现输入提示的功能呢?

更多阅读推荐

  • 云原生体系下的技海浮沉与理论探索

  • 如何通过 Serverless 轻松识别验证码?

  • 5G与金融行业融合应用的场景探索

  • 打破“打工人”魔咒,RPA 来狙击!

  • 使用 SQL 语句实现一个年会抽奖程序

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/515739.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

计算机与网络

文章目录1.计算机组成2.操作系统进程管理存储管理设备管理文件管理3.数据库系统关系代数数据仓库4.计算机网络1.计算机组成 计算机组成:控制器、运算器、存储设备、输入设备、输出设备。 控制器功能程序计数器(PC)下条要执行指令的地址指令…

物联网与万物互联有什么区别?

云栖号资讯:【点击查看更多行业资讯】 在这里您可以找到不同行业的第一手的上云资讯,还在等什么,快来! IoE与IoT:有什么区别? 除非您是专家,否则物联网(IoT)和万物互联(IoE)之间几乎没有什么区别。但是&am…

宝兰德中间件同台机器多个实例安装

文章目录1. 启动多实例2. 修改实例13. 修改实例21. 启动多实例 同一台机器同时启动两个示例ins-1和ins-2需要修改和规划端口避免冲突,端口配置在中间件安装目录下的conf/server.conf文件中。示例端口规划如下: 只需要修改http管理端口、http服务端口、J…

5G网络打破专有系统的桎梏

云栖号资讯:【点击查看更多行业资讯】 在这里您可以找到不同行业的第一手的上云资讯,还在等什么,快来! 随着技术的不断变迁,专有无线接入网络的时代正在逐渐消失。运营商希望能在降低成本的同时增加灵活性,…

为普及再助一把力!《2021年中国低代码/无代码市场研究报告》正式发布

开发能力“下放”,普通人也能通过“拖拉拽”快速搭建软件——在经历了大型套装软件、软件SaaS化之后,我国企业数字化进程即将迎来低代码/无代码开发的全新时代。 1月19日,海比研究院、中国软件网联合中国软件行业协会在北京举行《2021年中国…

微信小程序限制当前位置和目的地的距离

获取当前位置经纬度 onLoad: function (options) {var that this;campaign_id campaign_idwx.getLocation({type: wgs84,success: function (res) {console.log(res)lat1 res.latitude,lng1 res.longitude}})},通过点击事件打开地图选择位置 site: function () {var that …

软件设计师 - 数据库关系代数运算

文章目录1.交(∩)2.并(∪)3.差(-)4.投影(π)4.1.例子5.选择(σ)5.1.例子6.连接(⋈)6.1.等值连接6.2.自然连接6.4.外连接6.3.内连接7.笛…

阿里云CDN六大边缘安全能力,全力助推政企数字化转型

6月9日,2020年阿里云线上峰会召开。阿里云智能总裁张建锋认为,数字化已经成为中国经济的主要驱动力,疫情让政府、企业都认识到数字化的迫切性。在峰会上,阿里云CDN正式对外发布基于CDN构建的六大边缘安全能力,全力助推…

阿里云发布第七代云服务器ECS,整机算力提升160%

2020年6月9日,阿里云重磅发布第七代ECS企业级高主频实例以及新一代弹性裸金属云服务器,目前已启动邀测。 新一代的高主频实例搭载最新一代英特尔至强可扩展处理器(代号Cedar Island)以及阿里云自研的第三代神龙云服务器架构&…

PageHelper循环依赖 com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration

在用pageHelper的时候突然遇到个问题,启动项目后出现这个情况: springboot2.6好像禁止循环依赖还是啥的,翻来翻去没看到解决办法,后面去pageHelper github看,才看到最新版本已经解决了这个问题。 解决方案&#xff…

获奖名单出炉,快来看看有没有你!

这次千万别再错过!周五福利日,人人都可免费领会员!详情戳这里奖品多多,不仅有CSDN月卡会员、CSDN年卡会员,还有5w现金奖品等你瓜分!邀请越多奖品越多!本周五上午11:00,准点开放领取&…

看我如何用Dataphin实现自动化建模

前言:更多关于数智化转型、数据中台内容可扫码加群一起探讨 阿里云数据中台官网 https://dp.alibaba.com/index 作者:数据小海豚 随着大数据趋势的迅速增长,数据的重要性与日俱增,企业内看数据、用数据的诉求越来越强烈&#x…

EasyExcel 导出时 Converter转换器 注入 ExcelContentProperty 为null

异常现象: Converter转换器 注入 ExcelContentProperty 为null 直接原因: 调用**.head()**方法,重写表头样式,就导致ExcelContentProperty 注入失败。 源码原因: todo 解决办法: todo

SaaS模式云数据仓库:持续保护云上数据及服务安全

2020年6月9日,阿里云 MaxCompute 全新发布企业级新能力,在成本、性能、安全方面,持续定义企业级SaaS模式云数据仓库,通过 “云数据仓库” 的新模式,帮助企业实现数字经济新优势。 据介绍,最新发布的算力资…

springboot 集成flowable去除权限认证

参考SpringBoot集成Flowable-modeler模块并去除权限认证(二) /** * 单体启动类(采用此类启动项目为单体模式) */ Slf4j //排除flowable带的权限认证 SpringBootApplication(exclude {SecurityAutoConfiguration.class, org.springframework.boot.act…

看穿容器的外表,Linux容器实现原理演示

来源 | 多选参数责编 | 程序锅头图 | 下载于视觉中国容器技术的核心功能,就是通过约束和修改进程的动态表现,从而为其创造出一个“边界”也就是独立的“运行环境”。下面我们使用 C 语言和 Namespace 技术来手动创建一个容器,演示 Linux 容器…

小时候都想当科学家后来只有他做到了——对话阿里云MVP朱祺

云栖号资讯:【点击查看更多行业资讯】 在这里您可以找到不同行业的第一手的上云资讯,还在等什么,快来! 简介: 对朱祺我是好奇的。初次交流时,仅限于一个积极活跃、涉猎广泛的印象,拥抱新技术的传…

EasyExcel 导出

文章目录1.EasyExcel 导出1.1. Response流导出单sheet页1.1.1 response流处理(防止中文乱码):1.1.2 根据excel映射对象导出(适合结构化数据:列表台账)1.1.3. 根据单元格集合导出(适合非结构化数…

视频豪横时代,应用如何快速构建视频点播能力?

QuestMobile2020数据显示,疫情发生以来,每个网民每天花在移动互联网的时长比年初增加了21.5%,对于视频类应用增长尤为突出。而短视频用户规模已超8.5亿,用户使用时长在移动互联网用户使用总时长占比已达10.5%,仅次于社…

大数据的下一站是什么?服务/分析一体化

作者:蒋晓伟(量仔) 阿里巴巴研究员 因为侧重点的不同,传统的数据库可以分为交易型的 OLTP 系统和分析型的 OLAP 系统。随着互联网的发展,数据量出现了指数型的增长,单机的数据库已经不能满足业务的需求。特…