【问题标题】:create string pattern automatically自动创建字符串模式
【发布时间】:2021-11-24 21:24:18
【问题描述】:

需要根据给定的模式创建一个字符串。

如果模式是222243243,则需要创建的字符串是“2{4,6}[43]+2{1,3}[43]+”。 创建上述字符串的逻辑是,检查模式中有多少个 2 集合并计算它们并添加更多两个 2。这里包含两组 2。第一个包含 4 个 2,第二个部分包含 1 个 2。所以第一个 2 可以是 4 到 6(4+2) 个 2,第二个 2 可以是 1 到 3(1+2)。当有 3 或 4 时,[43]+ 需要添加。

工作原理:

import re
data='222243243'
TwosStart=[]#contains twos start positions
TwosEnd=[]#contains twos end positions
TwoLength=[]#number of 2's sets

for match in re.finditer('2+', data):
    s = match.start()#2's start position
    e = match.end()#2's end position
    d=e-s
    print(s,e,d)
    TwosStart.append(s)
    TwosEnd.append(e)
    TwoLength.append(d)

所以使用上面的代码,我知道给定模式中有多少个 2 组以及它们的开始和结束位置。但我不知道使用上述信息自动创建一个字符串。

例如:

if pattern '222243243' string should be "2{4,6}[43]+2{1,3}[43]+"

if pattern '222432243' string should be "2{3,5}[43]+2{2,4}[43]+"

if pattern '22432432243' string should be "2{2,4}[43]+2{1,3}[43]+2{2,4}[43]+"

【问题讨论】:

    标签: python python-3.x string logic


    【解决方案1】:

    一种方法是使用itertools.groupby

    from itertools import groupby
    
    s = "222243243"
    
    result = []
    for key, group in groupby(s, key=lambda c: c == "2"):
        if key:
            size = (sum(1 for _ in group))
            result.append(f"2{{{size},{size+2}}}")
        else:
            result.append("[43]+")
    
    pattern = "".join(result)
    print(pattern)
    

    输出

    2{4,6}[43]+2{1,3}[43]+
    

    【讨论】:

      【解决方案2】:

      使用您的基本代码:

      import re
      data='222243243'
      cpy=data
      offset=0 # each 'cpy' modification offsets the addition
      
      for match in re.finditer('2+', data):
          s = match.start() # 2's start position
          e = match.end() # 2's end position
          d = e-s
          regex = "]+2{" + str(d) + "," + str(d+2) + "}["
          cpy = cpy[:s+offset] + regex + cpy[e+offset:]
          offset+=len(regex)-d
      
      # sometimes the borders can have wrong characters
      if cpy[0]==']':
              cpy=cpy[2:] # remove "]+"
      else:
              cpy='['+cpy
      
      if cpy[len(cpy)-1]=='[':
              cpy=cpy[:-1]
      else:
              cpy+="]+"
      
      print(cpy)
      

      输出

      2{4,6}[43]+2{1,3}[43]+

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-08
        • 2017-04-20
        • 2021-12-05
        • 1970-01-01
        • 1970-01-01
        • 2021-07-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多