Python:如何在变量重复时增加计数

时间:2018-12-06 01:28:01

标签: python

我有一个txt文件,其中包含以下条目:

Rx = 34                  // Counter gets incremented = 1, since the Rx was found for the first time 
Rx = 2
Rx = 10
Tx = 2
Tx = 1
Rx = 3                   // Counter gets incremented = 2, since the Rx was found for the first time after Tx
Rx = 41
Rx = 3
Rx = 19

我只想增加第一次重复的“ Rx”的计数,而不是文本文件中所有Rx的计数。我的代码如下:

import re

f = open("test.txt","r")
count = 0

for lines in f:
    m = re.search("Rx = \d{1,2}", lines)
    if m:
        count +=1

print count

但这给了我txt文件中所有Rx的计数。我希望输出为2而不是7。

请帮帮我!

5 个答案:

答案 0 :(得分:0)

打破循环,因为您只需要查找重复。

import re

f = open("test.txt","r")
count = 0

for lines in f:
    m = re.search("Rx = \d{1,2}", lines)
    if m:
        count +=1
    if count >=2:
        break
print count

答案 1 :(得分:0)

if m:,只要m != 0,计数就会继续增加。如果只想获得前2个,则需要引入一些其他逻辑。

答案 2 :(得分:0)

import re

f = open("test.txt","r")
count = 0

for lines in f:
    m = re.search("Rx = \d{1,2}", lines)
    if m:
        count +=1
    if count >=2:
        break

print(m.group(0))

答案 3 :(得分:0)

如果要查找重复1x的Rx的计数:

import re
rx_count = {}
with open("test.txt","r") as f:
    count = 0
    for lines in f:
        if line.startswith('Rx'): rx_count[lines] = rx_count.get(lines,0)+1

现在您在rx_count中有一个计数器字典,我们过滤掉所有大于1的值,然后将这些值相加,然后打印出计数

rx_count = {k:v for k,v in rx_count.interitems() if v > 1}
count = sum(rx_count.values())

print count

答案 4 :(得分:0)

要完全按照自己的意愿进行操作,您需要跟踪已经看到的字符串。

您可以通过使用一组来跟踪您看到的内容直到重复,然后仅计算该字符串的出现次数来做到这一点。

这个例子可以做到

import re

count = 0
matches = set()

with open("test.txt", "r") as f:
    for line in f:
        m = re.search(r"Rx = \d{1,2}", line)
        if not m:
            # Skip the rest if no match
            continue

        if m.group(0) not in matches:
            matches.add(m.group(0))
        else:
            # First string we saw
            first = m.group(0)
            count = 2
            break

    for line in f:
        m = re.search(r"Rx = \d{1,2}", line)
        ## This or whatever check you want to do
        if m.group(0) == first:
            count += 1

print(count)