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

发布时间 2023-04-26 16:06:52作者: 高颜值的殺生丸

Pyahocorasick

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

安装Pyahocorasick

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

pip install pyahocorasick

使用Pyahocorasick

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

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)

  输出:

[('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命令进行安装:

pip install marisa-trie

  

使用Marisa_trie

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

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)

 

结果:

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

  

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