在不知道我在寻找什么的情况下找到字符串中模式的最佳方法?

2024-09-28 19:30:10 发布

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

我有不超过16种颜色的500x500位图,需要将其转换为文本文件,其中每种颜色由一个字符表示

然后,我需要通过在每行中查找模式来减小文本文件的大小

我现在有一个2D数组中的角色

例如:

AHAHAH = 3(AH)

HAHAHA = 3(HA)

AAAHHH = 3(A)3(H)

ABYZTT = ABYZ2(T)

AHAHAB = 2(AH)AB

我认为我不能使用正则表达式,因为有太多可能的组合

我甚至不知道从哪里开始


Tags: 角色ab颜色模式数组字符文本文件ha
1条回答
网友
1楼 · 发布于 2024-09-28 19:30:10

以下是我为解决我的问题所做的。 我还没有彻底检查edge案例,但它正在对我的测试输入进行处理。 也许这对将来的人会有帮助。 它是游程编码,但用于字符组,而不是单个字符。从我所读到的,正常的RLE将AAAAHA编码为A4H1A1H1A1,而我需要编码4A2HA

string='AHYAHYAHAHAHAHAHAHAHBBBBBBBTATAZAB*+I'
length=len(string)
half=round(length/2)
new_string=""
i=1
while i<=half and string:
  if i>length-i:
    pass
  sub_string1=string[:i]
  sub_string2=string[i:i+i]
  if sub_string1==sub_string2:
    match=True
    count=1
    while match is True:
        sub_string1=string[count*i:(count+1)*i]
        sub_string2=string[(count+1)*i:(count+2)*i]
        if sub_string1 == sub_string2:
          count+=1
        else:
          match=False
          new_string+="("+str(count+1)+")"+sub_string1
          string=string[count*i+i:]
          i=1
  else:  
    if i==len(string):
      new_string+=string[0]
      string=string[1:]
      i=1
    else:
      i+=1

print(new_string)
(2)AHY(7)AH(7)B(2)TAZAB*+I

相关问题 更多 >