python 如何匹配列表中某个单词_Python中部分指定单词的最佳匹配项
如果要重復(fù)執(zhí)行此操作,應(yīng)創(chuàng)建一個索引: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
總結(jié)
以上是生活随笔為你收集整理的python 如何匹配列表中某个单词_Python中部分指定单词的最佳匹配项的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 舰r4月28服务器维护,崩坏3 11月2
- 下一篇: sap运维要做哪些工作_患上腰椎间盘突出