繁体   English   中英

Python:比较两个字符串并返回它们共有的最长段

[英]Python: Compare two strings and return the longest segment that they have in common

作为Python的新手,我编写了一个工作函数,该函数将比较两个字符串并搜索两个字符串共享的最长子字符串。 例如,当函数比较“ goggle”和“ google”时,它将“ go”和“ gle”标识为两个常见的子字符串(不包括单个字母),但由于它是最长的,因此仅返回“ gle”。

我想知道我的代码的任何部分是否可以改进/重写,因为它可能被认为冗长且令人费解。 我也很高兴看到解决方案的其他方法。 提前致谢!

def longsub(string1, string2):
    sublist = []
    i=j=a=b=count=length=0

    while i < len(string1):
        while j < len(string2):
            if string1[i:a+1] == string2[j:b+1] and (a+1) <= len(string1) and (b+1) <= len(string2):
                a+=1
                b+=1
                count+=1
            else:
                if count > 0:
                    sublist.append(string1[i:a])
                count = 0
                j+=1
                b=j
                a=i
        j=b=0
        i+=1
        a=i

    while len(sublist) > 1:
        for each in sublist:
            if len(each) >= length:
                length = len(each)
            else:
                sublist.remove(each)

    return sublist[0]

编辑:比较“凝视”和“谷歌”可能是一个不好的例子,因为它们的长度相等,最长的共同段在相同的位置。 实际输入将更接近于此:“ xabcdkejp”和“ zkdieaboabcd”。 正确的输出应为“ abcd”。

在标准库中实际上恰好有一个函数: difflib.SequencMatcher.find_longest_match

编辑 :仅当单词在相同索引中具有最长的片段时,此算法才有效

您只需要一个循环就可以摆脱。 使用辅助变量。 像这样的东西(需要重构) http://codepad.org/qErRBPav

word1 = "google"
word2 = "goggle"

longestSegment = ""
tempSegment = ""

for i in range(len(word1)):
    if word1[i] == word2[i]:
        tempSegment += word1[i]
    else: tempSegment = ""

    if len(tempSegment) > len(longestSegment):
        longestSegment = tempSegment

print longestSegment # "gle"

编辑 :使用mgilson的建议find_longest_match (适用于不同段的位置):

from difflib import SequenceMatcher

word1 = "google"
word2 = "goggle"

s = SequenceMatcher(None, word1, word2)
match = s.find_longest_match(0, len(word1), 0, len(word2))

print word1[match.a:(match.b+match.size)] # "gle"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM