摆脱字符串中的重复块

时间:2013-10-30 18:51:32

标签: python regex string python-2.7

我有一个字符串被分成几对字母,我正在寻找一种方法来摆脱所有相同的字母对,通过在它们之间插入字符,形成新的对。此外,我希望一次拆分一对。到目前为止我设法做的是同时拆分所有相同的块,但这不是我正在寻找的。因此,例如,考虑“fr ee tr ee”。这应该是“fr eX et e e”,而不是“fr eXe tr eXe”。

有人有任何想法吗?

编辑:为了更清楚,我需要浏览字符串,并在“双块”的第一个实例中插入一个X,并在X的右边的所有内容上形成新的对。 “AA BB”,转到“AX AB B”。

到目前为止我已经

def FUN(text):
if len(text) < 2:
    return text

result = ""
for i in range(1, len(text), 2):
    if text[i] == text[i - 1]:
        result += text[i - 1] + "X" + text[i]
    else:
        result += text[i-1:i+1]

if len(text) % 2 != 0:
    result += text[-1]

return result

5 个答案:

答案 0 :(得分:1)

这个怎么样? :

r = list()
S = "free tree"
S = "".join(S.split())
s = list()
for i in range(0,len(S)) :
    s.append(S[i])
while len(s) > 0 :
    c1 = s.pop(0)
    c2 = 'X'
    if len(s) > 0 :
        if s[0]!=c1 :
            c2 = s.pop(0)
    else :
        c2 = ''
    r.append("{0}{1}".format(c1,c2))
result = " ".join(r)
print(result)

希望这会有所帮助:)

答案 1 :(得分:0)

您可以将字符串转换为列表并在循环中检查每个配对,然后在找到相同字符的位置之间插入另一个字符。现在处理代码将会编辑。

答案 2 :(得分:0)

my_string = "freetreebreefrost"
my_parts = [my_string[i:i+2] for i in range(0,len(my_string),2)]
final_list = []
while len(my_parts):
    part = my_parts.pop(0)
    if part in my_parts:
       tmp_str = part[1] +"".join(my_parts)
       my_parts = [tmp_str[i:i+2] for i in range(0,len(tmp_str),2)]
       final_list.append(part[0]+"X")
    else:
       final_list.append(part)

print final_list

可能有一个更酷的方法来做到这一点

答案 3 :(得分:0)

好的,这是:

s = "free tree aa"

def seperateStringEveryTwoChars(s):
    # get rid of any space
    s = s.replace(' ', '')
    x = ""
    for i, l in enumerate(s, 0):
        x += l
        if i % 2:
            x += ' '
    return x.rstrip()

def findFirstDuplicateEntry(stringList):
    for i, elem in enumerate(stringList, 0):

        if len(elem) > 1 and elem[0] == elem[1]:
            return i
    return None

def yourProgram(s):

    x = seperateStringEveryTwoChars(s)
    # print x  # debug only
    splitX = x.split(' ')
    # print splitX  # debug only
    i = findFirstDuplicateEntry(splitX)
    if i == None:
        return seperateStringEveryTwoChars(s)
    # print i  # debug only
    splitX[i] = splitX[i][0] + "X" + splitX[i][1]

    # print splitX  # debug only

    s = ''.join(splitX)
    # print s  # debug only
    # print "Done"  # debug only
    return yourProgram(s)

print yourProgram(s)

输出:

fr eX et ea a

输入字符串“aabbccddd”它将输出“aX ab bc cd dX d”

答案 4 :(得分:0)

这是一个简单的3行代码解决方案,单通,就像它一样容易 没有分裂,连接,数组,for循环,没有。

  1. 首先,从字符串中删除所有空格,将Replace_All \s+替换为“”

  2. Replace_All with callback ((.)(?:(?!\2)(.)|)(?!$))
    一个。如果(匹配3美元)替换为1美元 湾否则换成$ 1 +“X”

  3. 最后,在每2个字符之间加一个空格。 Replace_All (..)与$ 1 +“”

  4. 这是一个使用Perl的测试(不太了解Python)

     $str = 'ee ee rx xx tt bb ff fr ee tr ee';
    
     $str =~ s/\s+//g;
     $str =~ s/((.)(?:(?!\2)(.)|)(?!$))/ defined $3 ? "$1" : "$1X"/eg;
     $str =~ s/(..)/$1 /g;
    
     print $str,"\n";
    
     # Output:     
     # eX eX eX er xX xX xt tb bf fX fr eX et re e
    

     # Expanded regex
     #
     (                        # (1 start)
          ( . )               # (2)
          (?:
               (?! \2 )       # Not equal to the first char?
               ( . )          # (3) Grab the next one
            |  
                              # or matches the first, an X will be inserted here
          )
          (?! $ )
     )                        # (1 end)
    
相关问题