点此进入CSDN

点此添加QQ好友 加载失败时会显示




(一)pyahocorasick和marisa_trie,字符串快速查找的python包,自然语言处理,命名实体识别可用的高效包

Pyahocorasick

Pyahocorasick是一个基于AC自动机算法的字符串匹配工具。它可以用于快速查找多个短字符串在一个长字符串中的所有出现位置。Pyahocorasick可以在构建状态机时使用多线程,从而大大加快构建速度。

安装Pyahocorasick

Pyahocorasick可以使用pip命令进行安装:

1
pip install pyahocorasick

使用Pyahocorasick

以下是使用Pyahocorasick进行字符串匹配的示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import ahocorasick
 
# 构建模式匹配自动机
patterns = ['he', 'she', 'his', 'hers']
automaton = ahocorasick.Automaton()
for pattern in patterns:
    automaton.add_word(pattern, pattern)
automaton.make_automaton()
 
# 在文本中查找匹配
text = 'ushershewashis'
matches = []
for end_index, matched_pattern in automaton.iter(text):
    start_index = end_index - len(matched_pattern) + 1
    matches.append((matched_pattern, start_index, end_index))
print(matches)

  输出:

1
[('she', 1, 3), ('he', 2, 3), ('hers', 2, 5), ('she', 5, 7), ('he', 6, 7), ('his', 11, 13)]

  

Marisa_trie

Marisa_trie是一个高效的Trie树实现,可以用于存储和查找大量字符串。它能够压缩存储空间,并提供快速的前缀匹配和近似匹配功能。Marisa_trie还支持多种不同的序列化格式,可以在不同的程序和平台之间共享。

安装Marisa_trie

Marisa_trie可以使用pip命令进行安装:

1
pip install marisa-trie

  

使用Marisa_trie

以下是使用Marisa_trie进行字符串匹配的示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import marisa_trie
 
# 构建trie
short_strings = ['hello', 'world', 'python','py']
trie = marisa_trie.Trie(short_strings)
 
# 匹配长字符串
long_string = 'this is a hello world example using python hello'
 
results = []
for i in range(len(long_string)):
    matches = trie.prefixes(long_string[i:])
 
    # 输出匹配结果
    if matches:
        for matche in matches:
            results.append((matche,i,i+len(matche)))
 
print(results)

 

结果:

1
[('hello', 10, 15), ('world', 16, 21), ('py', 36, 38), ('python', 36, 42), ('hello', 43, 48)]

  

在以上示例代码中,我们首先构建了一个包含多个短字符串的Trie树。然后我们遍历文本中的所有前缀,并在Trie树中查找匹配的前缀。一旦找到匹配的前缀,我们可以计算匹配的起始和结束位置,并将它们添加到匹配列表中。

 

posted @   高颜值的殺生丸  阅读(192)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
历史上的今天:
2020-04-26 实体识别中,或序列标注任务中的维特比Viterbi解码

作者信息

昵称:

刘新宇

园龄:4年6个月


粉丝:1209


QQ:522414928

点击右上角即可分享
微信分享提示