如何使用pygtrie从文本中找出已添加到Trie的所有词汇?
在文本中检索pygtrie存储的键值
pygtrie本身没有提供直接从文本中检索所有已存键的方法,你需要自己实现这个逻辑。核心思路是遍历文本中所有可能的连续词组合,检查是否存在于Trie中,具体步骤如下:
1. 修正初始化代码的小问题
首先注意Python的布尔值是大写的True,不是小写true,修正后的初始化代码:
from pygtrie import Trie trie = Trie() trie["Grand Canyon"] = True trie["New York"] = True
2. 实现文本检索函数
下面的函数会提取文本中的单词,生成所有连续词组合并检查是否在Trie中,最终返回所有匹配的键:
import re def find_trie_keys_in_text(trie, text): # 提取文本中的单词(去除标点符号) words = re.findall(r'\b\w+\b', text) matches = set() total_words = len(words) # 先获取Trie中键的最大单词数,减少不必要的循环 max_word_length = max(len(key.split()) for key in trie.keys()) if trie else 0 for start_idx in range(total_words): # 内层循环最多到start_idx + max_word_length,避免无效遍历 end_idx_max = min(start_idx + max_word_length, total_words) for end_idx in range(start_idx + 1, end_idx_max + 1): candidate_key = ' '.join(words[start_idx:end_idx]) if candidate_key in trie: matches.add(candidate_key) return list(matches)
3. 测试使用
调用函数测试你的目标文本:
target_text = "Grand Canyon, New York, I like strawberries." matches = find_trie_keys_in_text(trie, target_text) print(matches) # 输出: ['Grand Canyon', 'New York']
可选优化:忽略大小写匹配
如果需要忽略文本和Trie键的大小写差异,可以修改代码统一转成小写:
# 初始化Trie时用小写键 trie["grand canyon"] = True trie["new york"] = True def find_trie_keys_in_text(trie, text): words = re.findall(r'\b\w+\b', text.lower()) # 文本转小写 matches = set() total_words = len(words) max_word_length = max(len(key.split()) for key in trie.keys()) if trie else 0 for start_idx in range(total_words): end_idx_max = min(start_idx + max_word_length, total_words) for end_idx in range(start_idx + 1, end_idx_max + 1): candidate_key = ' '.join(words[start_idx:end_idx]) if candidate_key in trie: matches.add(candidate_key.title()) # 转回标题格式输出,或者直接返回小写 return list(matches)
内容的提问来源于stack exchange,提问作者Ian
相关产品推荐
相关产品推荐

