在python字符串中匹配大小写

2024-10-02 10:34:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个函数来检查一个单词是否在字符串中,或者该单词是否与字符串中的每个单词有len(word)-1个共同的字符。你知道吗

例如:

word: match   string: There is a match   -> True
word: matck   string: There is a match   -> True

对于这两个示例,输出都必须为True,因为matck-1=matcmatch-1=matc

到目前为止,我已经编写了以下代码:

for idx, f in enumerate(files):
    for word in words:
        if term in f:
            numOfWord[idx] += 1
        else:
            file_words = f.split()
            for f_word in file_words:
                if word[:-1] == file_word[:-1]:
                    numOfWords[idx] += 1

但这并不好,因为我有一个非常大的word列表和非常大的长文件目录,所以运行时间是不现实的。你知道吗


Tags: 字符串intrueforstringismatch单词
1条回答
网友
1楼 · 发布于 2024-10-02 10:34:27

你可以用Levenshtein距离来检查

def minimumEditDistance(s1,s2):
if len(s1) > len(s2):
    s1,s2 = s2,s1
distances = range(len(s1) + 1)
for index2,char2 in enumerate(s2):
    newDistances = [index2+1]
    for index1,char1 in enumerate(s1):
        if char1 == char2:
            newDistances.append(distances[index1])
        else:
            newDistances.append(1 + min((distances[index1],
                                         distances[index1+1],
                                         newDistances[-1])))
    distances = newDistances
return distances[-1]


print(minimumEditDistance("kitten","sitting"))
print(minimumEditDistance("rosettacode","raisethysword"))

https://rosettacode.org/wiki/Levenshtein_distance#Python

相关问题 更多 >

    热门问题