ahocorasick库的使用

应用

  • 能够ner保底,将历史出现的实体识别出来
  • 能够一定程度上解决实体嵌套的问题
  • 能够作为实体标注使用

代码示例

import ahocorasick


def search_keyword(text, keywords):
    # 创建 AhoCorasick 自动机对象
    trie = ahocorasick.Automaton()

    # 添加模式到自动机中
    for index, keyword in enumerate(keywords):
        trie.add_word(keyword, (index, keyword))

    # 完成模式的添加
    trie.make_automaton()

    # 在文本中搜索关键词
    matches = []
    for end_index, (keyword_index, keyword) in trie.iter(text):
        start_index = end_index - len(keyword) + 1
        matches.append((start_index, end_index, keyword))

    return matches


# 测试
text = "今天是个好日子,我想去公园玩。"
keywords = ["好日子", "公园", "公"]
result = search_keyword(text, keywords)
print(result)

posted @ 2023-08-22 16:54  时光如你般美好  阅读(194)  评论(0编辑  收藏  举报