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

2024-04-20 11:22:18 发布

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

我想找到以下两个字符串之间的公共字符串: 字符串列表=['PS1 123456测试','PS1 758922测试','PS1 978242测试']

下面的代码只返回第一部分“PS1”,我可以想象结果是“PS1测试”。你能帮我一下吗,可以用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

Tags: 字符串代码in列表fordefmatchcommon
2条回答

这是没有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']

现在,您可以简单地进行一组交集来查找公共元素。参考:Python -Intersection of multiple lists?

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:]))

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

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在你的案子中做得很好。我们得到的不仅仅是普通的单词,还有单词片段,非常令人印象深刻

相关问题 更多 >