为了账号安全,请及时绑定邮箱和手机立即绑定

使用 SequenceMatcher 在多个字符串中查找公共片段

使用 SequenceMatcher 在多个字符串中查找公共片段

交互式爱情 2024-01-27 15:20:28
我想找到以下之间的公共字符串: strings_list = ['PS1 123456 Test', 'PS1 758922 Test', 'PS1 978242 Test']以下代码仅返回第一部分“PS1 1”,我想结果是“PS1 Test”。你能帮我一下,是否可以使用SequenceMatcher获取?先感谢您!def findCommonStr(strings_list: list) -> str:        common_str = strings_list[0]        for i in range(1, n):            match = SequenceMatcher(None, common_str, strings_list[i]).get_matching_blocks()[0]                  common_str = common_str[match.b: match.b + match.size]        common_str = common_str.strip()        return common_str
查看完整描述

2 回答

?
哔哔one

TA贡献1854条经验 获得超8个赞

这是没有 SequenceMatcher 方法的情况。如果所有字符串都遵循相同的模式,您可以将它们分成空格上的单词。


strings_list = ['PS1 123456 Test', 'PS1 758922 Test', 'PS1 978242 Test']


test = []

for string in strings_list:

  print(string.split())

  test.append(string.split())


>>> ['PS1', '123456', 'Test']

['PS1', '758922', 'Test']

['PS1', '978242', 'Test']

现在您可以简单地进行集合交集来查找公共元素。

set(test[0]).intersection(*test[1:])


>>> {'PS1', 'Test'}


# join them to get string

' '.join(set(test[0]).intersection(*test[1:]))


>>> PS1 Test

只有当它们遵循这种由空格分隔的模式时,这才有效。


功能:


def findCommonStr(strings_list: list) -> str:


  all_str = []

  for string in strings_list:

    

    all_str.append(string.split())


  return ' '.join(set(all_str[0]).intersection(*all_str[1:]))


查看完整回答
反对 回复 2024-01-27
?
GCT1015

TA贡献1827条经验 获得超4个赞

您需要保留所有片段,而不仅仅是第一个片段:


def get_common_str(strs: List[str]) -> str:

    common_str = strs[0] if strs else ''


    for str_ in strs[1:]:

        common_str = ''.join(

            common_str[m.a:m.a + m.size]

            for m in SequenceMatcher(None, common_str, str_).get_matching_blocks()

        )


    return common_str



print(get_common_str(['PS1 123456 Test', 'PS1 758922 Test', 'PS1 978242 Test']))

这使


PS1 2 Test

这个问题很棘手,所以这种启发式可能并不总是有效,请随意想出另一个!看起来 SequenceMatcher 在你的案例中做得很好。我们不仅得到了常见的单词,还得到了单词片段,令人印象深刻。


查看完整回答
反对 回复 2024-01-27
  • 2 回答
  • 0 关注
  • 43 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信