代码之家  ›  专栏  ›  技术社区  ›  Nope

python:re..查找最长序列

  •  1
  • Nope  · 技术社区  · 16 年前

    我有一个随机生成的字符串:

    polymer_str = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine"
    

    我想找出最长的“丁二醇”序列和最长的“丁二胺”。因此,在上面的情况下,最长的“DINCO二醇”序列是1,最长的“DINCO二胺”是3。

    我该如何使用Python的re模块来实现这一点呢?

    事先谢谢。

    编辑:
    我是指给定字符串的最长重复次数。因此,最长的“dinco diamine”字符串是3:
    二醇 迪科二胺迪科二胺迪科二胺 丁二醇丁二胺

    5 回复  |  直到 16 年前
        1
  •  5
  •   Community Mohan Dere    9 年前

    扩展在 Ealdwulf answer :

    文件 re.findall 可以找到 here .

    def getLongestSequenceSize(search_str, polymer_str):
        matches = re.findall(r'(?:\b%s\b\s?)+' % search_str, polymer_str)
        longest_match = max(matches)
        return longest_match.count(search_str)
    

    这可以写成一行,但在这种形式下它的可读性会降低。

    替代方案:

    如果 polymer_str 是巨大的,使用它会更节省内存 re.finditer . 你可以这样做:

    def getLongestSequenceSize(search_str, polymer_str):
        longest_match = ''
        for match in re.finditer(r'(?:\b%s\b\s?)+' % search_str, polymer_str):
            if len(match.group(0)) > len(longest_match):
                longest_match = match.group(0)
        return longest_match.count(search_str)
    

    最大的区别在于 findall finditer 第一个返回列表对象,第二个迭代匹配对象。此外, 发现者 方法会稍微慢一些。

        2
  •  3
  •   Ealdwulf    16 年前

    我认为操作需要最长的连续序列。您可以获取所有连续序列,如: seqs=re.findall(“(?):dinco diamine)+“,聚合物_str)

    然后找到最长的。

        3
  •  3
  •   ghostdog74    16 年前
    import re
    pat = re.compile("[^|]+")
    p = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine".replace("diNCO diamine","|").replace(" ","")
    print max(map(len,pat.split(p)))
    
        4
  •  0
  •   Sinan Taifour    16 年前

    一种是使用 findall :

    polymer_str = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine"
    len(re.findall("diNCO diamine", polymer_str)) # returns 4.
    
        5
  •  0
  •   lutz    16 年前

    使用RE:

     m = re.search(r"(\bdiNCO diamine\b\s?)+", polymer_str)
     len(m.group(0)) / len("bdiNCO diamine")