欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python 如何匹配列表中某个单词_Python中部分指定单词的最佳匹配项

发布时间:2025/3/12 python 31 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python 如何匹配列表中某个单词_Python中部分指定单词的最佳匹配项 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

如果要重复执行此操作,应创建一个索引:wordlist = [word.strip() for word in "run, ran, rat, rob, fish, tree".split(',')]

from collections import defaultdict

class Index(object):

def __init__(self, wordlist=()):

self.trie = defaultdict(set)

for word in wordlist:

self.add_word(word)

def add_word(self, word):

""" adds word to the index """

# save the length of the word

self.trie[len(word)].add(word)

for marker in enumerate(word):

# add word to the set of words with (pos,char)

self.trie[marker].add(word)

def find(self, pattern, wildcard='-' ):

# get all word with matching length as candidates

candidates = self.trie[len(pattern)]

# get all words with all the markers

for marker in enumerate(pattern):

if marker[1] != wildcard:

candidates &= self.trie[marker]

# exit early if there are no candicates

if not candidates:

return None

return candidates

with open('dict.txt', 'rt') as lines:

wordlist = [word.strip() for word in lines]

s = Index(wordlist)

print s.find("r--")

Tries用于搜索字符串。这是一个简单的前缀trie,使用一个dict

总结

以上是生活随笔为你收集整理的python 如何匹配列表中某个单词_Python中部分指定单词的最佳匹配项的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。