[英]find best subset from list of strings to match a given string
我有一個弦
s = "mouse"
和一個字符串列表
sub_strings = ["m", "o", "se", "e"]
我需要找出匹配s的列表中sub_strings的最佳和最短匹配子集是什么。 做這個的最好方式是什么? 理想的結果是[“ m”,“ o”,“ se”],因為它們一起拼寫了mose
import difflib
print difflib.get_close_matches(target_word,list_of_possibles)
但不幸的是,它對於上面的示例不起作用,您可以改用Levenstein距離...
def levenshtein_distance(first, second):
"""Find the Levenshtein distance between two strings."""
if len(first) > len(second):
first, second = second, first
if len(second) == 0:
return len(first)
first_length = len(first) + 1
second_length = len(second) + 1
distance_matrix = [[0] * second_length for x in range(first_length)]
for i in range(first_length):
distance_matrix[i][0] = i
for j in range(second_length):
distance_matrix[0][j]=j
for i in xrange(1, first_length):
for j in range(1, second_length):
deletion = distance_matrix[i-1][j] + 1
insertion = distance_matrix[i][j-1] + 1
substitution = distance_matrix[i-1][j-1]
if first[i-1] != second[j-1]:
substitution += 1
distance_matrix[i][j] = min(insertion, deletion, substitution)
return distance_matrix[first_length-1][second_length-1]
sub_strings = ["mo", "m,", "o", "se", "e"]
s="mouse"
print sorted(sub_strings,key = lambda x:levenshtein_distance(x,s))[0]
這將始終為您提供與目標“最接近”的詞(用於一些最接近的定義)
levenshtein函數從以下位置被盜:http://www.korokithakis.net/posts/finding-the-levenshtein-distance-in-python/
您可以使用正則表達式:
import re
def matches(s, sub_strings):
sub_strings = sorted(sub_strings, key=len, reverse=True)
pattern = '|'.join(re.escape(substr) for substr in sub_strings)
return re.findall(pattern, s)
這至少是簡短而快速的,但不一定能找到最佳的匹配項。 太貪心了 例如,
matches("bears", ["bea", "be", "ars"])
返回["bea"]
,應在何時返回["be", "ars"]
。
代碼說明:
第一行按長度對子字符串進行排序,以使最長的字符串出現在列表的開頭。 這確保了正則表達式將首選長匹配而不是短匹配。
第二行創建由所有子字符串組成的正則表達式模式,用|
分隔|
符號,表示“或”。
第三行僅使用re.findall
函數查找給定字符串s
模式的所有匹配項。
該解決方案基於用戶Running Wild的 答案 。 它使用Stefan Behnel提供的acora
軟件包,通過Aho–Corasick算法有效地找到目標中子字符串的所有匹配項,然后使用動態編程來找到答案。
import acora
import collections
def best_match(target, substrings):
"""
Find the best way to cover the string `target` by non-overlapping
matches with strings taken from `substrings`. Return the best
match as a list of substrings in order. (The best match is one
that covers the largest number of characters in `target`, and
among all such matches, the one using the fewest substrings.)
>>> best_match('mouse', ['mo', 'ou', 'us', 'se'])
['mo', 'us']
>>> best_match('aaaaaaa', ['aa', 'aaa'])
['aaa', 'aa', 'aa']
>>> best_match('abracadabra', ['bra', 'cad', 'dab'])
['bra', 'cad', 'bra']
"""
# Find all occurrences of the substrings in target and store them
# in a dictionary by their position.
ac = acora.AcoraBuilder(*substrings).build()
matches = collections.defaultdict(set)
for match, pos in ac.finditer(target):
matches[pos].add(match)
n = len(target)
# Array giving the best (score, list of matches) found so far, for
# each initial substring of the target.
best = [(0, []) for _ in xrange(n + 1)]
for i in xrange(n):
bi = best[i]
bj = best[i + 1]
if bi[0] > bj[0] or bi[0] == bj[0] and len(bi[1]) < bj[1]:
best[i + 1] = bi
for m in matches[i]:
j = i + len(m)
bj = best[j]
score = bi[0] + len(m)
if score > bj[0] or score == bj[0] and len(bi[1]) < len(bj[1]):
best[j] = (score, bi[1] + [m])
return best[n][1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.