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

Python:如何在变量重复时增加计数,python,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

我有一个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


请帮帮我

打破循环,因为你只需要找出重复

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

通过说
如果m:
只要
m!=0
。如果只想得到前2个,则需要引入一些附加逻辑。

如果要查找重复1x的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
    if count >=2:
        break

print(m.group(0))
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

要准确地执行您想要的操作,您需要跟踪您已经看到的字符串

您可以通过使用一个集合来跟踪所看到的内容,直到有重复的内容,然后只计算该字符串的出现次数

这个例子可以做到这一点

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)

这将始终输出0、1或2。我认为理想的输出将是
m.group(0)
。我把这作为一个单独的答案,但如果你编辑你的文章,我会给你分。