模式匹配迅速入手——ahocorasick第三方数据库的使用

模式匹配主要的功能类似于我之前根据词性进行摘取单词一样,就是通过字典去摘取这些单词

 

 

 类似于这样的效果

代码:

 1 # # -*- coding:utf-8 -*-
 2 # @Time : 2020/11/28 20:24 
 3 # @Author : 周博
 4 # @File : test_3.py 
 5 # @博客园: https://www.cnblogs.com/smartisn/
 6 
 7 #coding:utf-8
 8 import ahocorasick
 9 
10 def make_AC(AC, word_set):
11     for word in word_set:
12         print(word)
13         AC.add_word(word,word)
14     return AC
15 
16 def test_ahocorasick():
17     '''
18     ahocosick:自动机的意思
19     可实现自动批量匹配字符串的作用,即可一次返回该条字符串中命中的所有关键词
20     '''
21     key_list = ["苹果", "香蕉", "", "橙子", "柚子", "火龙果", "柿子", "猕猴挑"]
22     AC_KEY = ahocorasick.Automaton()
23     AC_KEY = make_AC(AC_KEY, set(key_list))
24     AC_KEY.make_automaton()
25     test_str_list = ["我最喜欢吃的水果有:苹果、梨和香蕉", "我也喜欢吃香蕉,但是我不喜欢吃梨"]
26     for content in test_str_list:
27         name_list = set()
28         for item in AC_KEY.iter(content):#将AC_KEY中的每一项与content内容作对比,若匹配则返回
29             name_list.add(item[1])
30         name_list = list(name_list)
31         if len(name_list) > 0:
32             print(content, "--->命中的关键词有:", "\t".join(name_list))
33 if __name__ == "__main__":
34     test_ahocorasick()

来源: python ahocorasick介绍_u010569893的博客-CSDN博客

posted @ 2020-11-28 20:31  博二爷  阅读(383)  评论(0编辑  收藏  举报