巧合的字符串搜索?

问题描述

我只是想知道是否有一种简单的方法可以通过 Python 中的另一个字符串来搜索一个字符串。或者如果有人知道如何做到这一点。

为了清楚起见,我举个例子。

text_sample = "baguette is a french word"
words_to_match = ("baguete","wrd")

letters_to_match = ('b','a','g','u','t','e','w','r','d')   #   With just one 'e'
coincidences = sum(text_sample.count(x) for x in letters_to_match)

#    coincidences = 14 Current output
#    coincidences = 10 Expected output

我当前的方法words_to_match 分解为单个字符,如 letters_to_match 中那样,但随后匹配如下:“baguette is a f 重新nch word" (coincidences = 14)。

但我想获得 (coincidences = 10) 其中 "baguette 是法语 word ”被视为巧合。通过检查 words_to_matchtext_sample 中的单词之间的相似性。

如何获得预期的输出

解决方法

看起来您需要最长公共子序列 (LCS) 的长度。参见 the algorithm in the Wikipedia article 来计算它。您也可以找到一个可以快速计算它的 C 扩展。例如,this search 有很多结果,包括 pylcs。安装后 (pip install pylcs):

import pylcs
text_sample = "baguette is a french word"
words_to_match = ("baguete","wrd")
print(pylcs.lcs2(text_sample,' '.join(words_to_match.join)))  #: 14
,

首先,将 words_to_match 拆分为

    words = ''
    for item in words_to_match:
        words += item
    letters = [] # create a list
    for letter in words:
        letters.append(letter)
    letters = tuple(letters)

然后,看看它是否在里面

    x = 0
    for i in sample_text:
        if letters[x] == i:
            x += 1
            coincidence += 1

如果它不是按顺序做的:

    for i in sample_text:
        if i in letters: coincidence += 1

(请注意,某些版本的 python 需要换行)