Skip to main content
 首页 » 编程设计

python之计算具有特定字符的行后的行数

2025年05月04日13xxx_UU

我有一个包含这些数据的文件:

>P136 
FCF#0.73 
FCF#0.66 
FCF#0.86 
>P129 
FCF#0.72 
>P142 
>P144 
>P134 
FCF#0.70 
FCF#0.82 

我需要计算包含 ">"的行之后的行数,但保留 ">"行作为引用,对于这个例子,输出应该是:

>P136 3 
>P129 1 
>P134 2 

有什么想法吗?

请您参考如下方法:

使用字典存储每行的计数,每次开始时没有>,增加计数:

counts = {} 
current = None 
 
with open(filename) as fo: 
   for line in fo: 
       if line.startswith('>'): 
           current = line.strip() 
           counts[current] = 0 
       else: 
           counts[current] += 1 

然后简单地循环并打印计数:

for entry, count in counts.items(): 
    print('{} {:2d}'.format(entry, count)) 

您甚至可以在每次找到新部分时只打印数字:

count = 0 
current = None 
 
with open(filename) as fo: 
   for line in fo: 
       if line.startswith('>'): 
           if current and count: 
               print('{} {:2d}'.format(entry, count)) 
           current = line.strip() 
           counts = 0 
       else: 
           count += 1 
   if current and count: 
       print('{} {:2d}'.format(entry, count)) 

但是您无法轻松地将计数重新用于其他工作。