1

我正在尝试检查是否在打开文档的特定行上执行了正则表达式,如果是,则将计数变量添加 1。如果计数超过 2,我希望它停止。下面的代码是我到目前为止所拥有的。

for line in book:
    if count<=2:
            reg1 = re.sub(r'Some RE',r'Replaced with..',line)
            f.write(reg1)
            "if reg1 was Performed add to count variable by 1"
4

5 回答 5

4

Definitely the best way of doing this is to use re.subn() instead re.sub()

The re.subn() returns a tuple (new_string, number_of_changes_made) so it's perfect for you:

for line in book:
    if count<=2:
        reg1, num_of_changes = re.subn(r'Some RE',r'Replaced with..',line)
        f.write(reg1)
        if num_of_changes > 0:
            count += 1
于 2013-07-15T17:39:09.243 回答
2

如果这个想法是确定是否在行上执行了替换,则相当简单:

count = 0
for line in book:
    if count<=2:
        reg1 = re.sub(r'Some RE',r'Replaced with..',line)
        f.write(reg1)
        count += int(reg1 == line)
于 2013-07-15T16:59:25.913 回答
1

您可以将函数传递给re.sub作为替换值。这可以让你做这样的事情:(虽然一个简单的搜索然后子方法虽然更慢会更容易推理):

import re

class Counter(object):
    def __init__(self, start=0):
        self.value = start

    def incr(self):
        self.value += 1

book = """This is some long text
with the text 'Some RE' appearing twice:
Some RE see?
"""

def countRepl(replacement, counter):
    def replacer(matchobject):
        counter.incr()
        return replacement

    return replacer

counter = Counter(0)

print re.sub(r'Some RE', countRepl('Replaced with..', counter), book)

print counter.value

这会产生以下输出:

This is some long text
with the text 'Replaced with..' appearing twice:
Replaced with.. see?

2
于 2013-07-15T17:29:23.590 回答
0

subn 将告诉您在该行中进行了多少次替换,并且 count 参数将限制将尝试的替换次数。将它们放在一起,您的代码将在两次替换后停止,即使一行中有多个子。

look_count = 2
for line in book:
    reg1, sub_count = re.subn(r'Some RE', r'Replaced with..', line,count=look_count)
    f.write(reg1)
    look_count -= sub_count
    if not look_count:
        break
于 2013-07-15T18:38:00.457 回答
0

您可以将其与原始字符串进行比较以查看它是否已更改:

for line in book:
    if count<=2:
        reg1 = re.sub(r'Some RE',r'Replaced with..',line)
        f.write(reg1)
        if line != reg1:
            count += 1
于 2013-07-15T16:58:39.537 回答