自动创建字符串模式

2024-10-01 07:43:23 发布

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

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

如果模式是222243243则需要创建的字符串是“2{4,6}[43]+2{1,3}[43]+”。 创建上述字符串的逻辑是,检查模式中有多少个2的集合,并对它们进行计数,然后再添加两个2。第一部分包含4个2,第二部分包含1个2。因此,前两个可以是4到6(4+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]+"

Tags: 字符串redatastringifmatch模式be
2条回答

一种方法是使用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]+

使用基本代码:

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]+

相关问题 更多 >