【问题标题】:Python Replace consecutive letters with different variablesPython用不同的变量替换连续的字母
【发布时间】:2017-03-11 17:30:43
【问题描述】:

我希望有一个简单的问题。我只是想不出要使用的正确功能。我想根据连续重复的次数用不同的变量替换重复字符。

使用 open("text1.txt","r") 作为文件: 对于文件中的行: 计数 = line.count('a') 如果计数 == 1: Line1 = line.replace('a', '1') 打印(第 1 行) elif 计数 == 2: Line1 = line.replace('aa', '2') 打印(第 1 行)

所以如果“a”连续重复 3 次,我想用 3 替换“aaa”,依此类推,最多 9 次。问题是,无论其是否连续,计数它们都很重要。如果我一次读一行 2 个或 3 个字符,它就会把它切碎。请有任何想法或帮助。

【问题讨论】:

    标签: python python-3.x replace counting


    【解决方案1】:

    如果您想分析/替换连续的字母组,那么itertools.groupby 可能会很有趣。下面的示例首先提取所有连续组,然后检查特定组中的唯一元素是否为a。如果是,则将这个组替换为相应的元素数,否则,保留原始输入。

    from itertools import groupby
    
    s = 'aaabaacdd' #test input
    
    ret = ''
    for k, v in groupby(s):
        chunk = list(v)
        cnt = len(chunk)
    
        if k == 'a': #the condition can be extended here, e.g., k == 'a' and cnt <= 9
            #substitute the group of 'a's with something else
            #the substitution can take into account the number of consecutive
            #'a's stored in the variable cnt
            el = '%d' % (cnt)
        else:
            el = ''.join(chunk)
        ret += el
    print(ret)
    

    生产

    3b2cdd
    

    【讨论】:

    • 我认为那是合适的,但我没有把我的问题说得足够清楚。这只是计算'a''的数量并放置长度。我怎么能改变它把我想要的东西作为变量所以'aaa'将是'Z'而不是3。它会改变。
    • @LetsChangeTheWorld 然后只需将el = '%d' % (cnt) 替换为您要使用的替换,例如el = 'Z'
    • 谢谢你的解释,这实际上帮助我理解了这一切到底在做什么。我能够很快将其放入读取文件中。
    【解决方案2】:

    字符串(一行)的简单解决方案。您可以扩展它来读取文件。

    f = 'a b aa b aaa b'
    output = f
    
    for i in range(9,0,-1):
        output = output.replace('a' * i, str(i))
    
    print(output)  # 1 b 2 b 3 b
    

    【讨论】:

      猜你喜欢
      • 2021-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多