在python中计算相同字符的组

在python中计算相同字符的组,python,line-count,Python,Line Count,我有这样一个输入文件: ccccccccccccccccbbbbbbbbccccccccccccccccccccc 我想数一数每组有多少个“B”。因此,输出将是: B:3,11,1 我尝试了两个不同的脚本,但都给出了B=15的总数 以下是我的一个尝试: import collections with open('input.txt') as infile: counts = collections.Counter(B.strip() for B in infile) for l

我有这样一个输入文件:

ccccccccccccccccbbbbbbbbccccccccccccccccccccc

我想数一数每组有多少个“B”。因此,输出将是:

B:3,11,1

我尝试了两个不同的脚本,但都给出了B=15的总数

以下是我的一个尝试:

import collections

with open('input.txt') as infile:  
    counts = collections.Counter(B.strip() for B in infile)  
for line, count in counts.most_common():  
    print line, count 
请尝试以下方法:

with open('input.txt') as infile:  
    counts = [i.count('B') for i in infile]

>>>print(counts)
 
[3, 11, 1]

这是
itertools.groupby
的一个很好的应用程序,它将类似值的输入分组到子迭代器中

>>> import itertools
>>> text="CCCCCCCCCCCCCBBBCCBBBBBBBBBBBCCCCCCCCCCCCCCCCBCCC"
>>> b_counts = []
>>> for letter, repeats in itertools.groupby(text):
...     if letter == "B":
...             b_counts.append(len(list(repeats)))
... 
>>> b_counts
[3, 11, 1]
看起来很简单

def countBGroups(S):

    groups = []
    c = 0

    for s in S:

        if s == "B":
            c += 1
        else:
            if c != 0:
                groups.append(c)
            
            c = 0
    
    if c != 0:
        groups.append(c)
    
    return groups

with open("input.txt") as f:

    print(countBGroups(f.read()))

尝试使用
“B”
而不是
B
。我尝试了它不起作用。请解释您更改了什么以及代码是如何工作的。这是一个很好的解决方案,非常“pythonic”,但对于学习的人来说,最好添加一个关于它如何工作的描述。
I
在本例中没有定义。看起来你是在计算文件每一行中的B的数量,而不是一行中的B组。谢谢。这很有效