使用正则表达式(或另一个python模块)来比较文本/字符?

2024-06-25 07:24:12 发布

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

假设我的程序接收到一个输入,比如一个具有任何类型字符的字符串。例如,“鲍勃百吉饼店”。然后它得到另一个字符串,写着“弗雷德百吉饼店”。如何在python中使用正则表达式或其他模块来比较这些字符,并让我的程序告诉我是否至少有5个字符(或我想要的任何数字)在字符串中的任何位置都是相同的,但所有字符的顺序都相同,例如单词“Bagel”?在

谢谢。在


Tags: 模块字符串程序类型顺序数字字符单词
3条回答

您可以使用itetools.combinations,然后使用集合的intersection从两个字符串中找出匹配的字符:

from itertools import combinations
str1="Bob's Bagel Shop"
str2="Fred's Bagel Store"

def combi(strs):
    chars=''.join(strs.split())
    lis=[]
    for x in range(1,len(chars)):
        for y in combinations(chars,x):
            if ''.join(y) in chars:
                lis.append(''.join(y))
    return lis           


lis1=combi(str1)
lis2=combi(str2)
print max(set(lis1).intersection(set(lis2)),key=len)  

输出:

^{pr2}$

有一个Python标准库类^{}可以帮助您解决问题。下面是一个代码示例:

from difflib import SequenceMatcher

s1 = "Bob's Bagel Shop"
s2 = "Bill's Bagel Shop"

matcher = SequenceMatcher(a=s1, b=s2)
match = matcher.find_longest_match(0, len(s1), 0, len(s2))

结果:

^{pr2}$

结果表明,两个字符串都有相同的13个字符长度的子字符串(从第一个字符串的第三个字符开始,第二个字符串的第四个字符开始)。在

可以使用此匹配结果对象获取其字段作为值:

match.size  # 13
match.a     # 3
match.b     # 4

相关问题 更多 >