【问题标题】:How to count instances of a string and replace them with another string + the current counter?如何计算字符串的实例并用另一个字符串+当前计数器替换它们?
【发布时间】:2019-12-15 12:24:20
【问题描述】:

道歉:我是编程新手。老实说,我努力让它发挥作用。我认为我了解问题所在,但不了解如何解决。我在代码中使用了这个论坛上的一些已回答问题,但这还不够。

起点:我有一个 txt 文件。在这个 txt 文件中,一些行包含一个特定的字符串,'<lb n=""/>',而其他行不包含。 以这个为例

<lb n=""/>magna quaestio
<lb n=""/>facile solution
<pb n="5"/>
<lb n=""/>amica responsum

目标:我要对字符串&lt;lb n=""/&gt;每行进行计数,并将当前计数器填入字符串中。

所以在运行脚本后,示例应该如下所示:

<lb n="1"/>magna quaestio
<lb n="2"/>facile solution
<pb n="5"/>
<lb n="3"/>amica responsum

下面是我脚本的相关部分。

问题:使用我的脚本时,每个字符串都被替换为总计数器&lt;lb n="464"&gt; 而不是当前的。

代码:

def replace_text(text):
    lines = text.split("\n")
    i = 0
    for line in lines:
        exp1 = re.compile(r'<lb n=""/>')                            # look for string
        if '<lb n=""/>' in line:                                    # if string in line
            text1 = exp1.sub('<lb n="{}"/>'.format(i), text)        # replace with lb-counter
            i += 1
    return text1

您能告诉我如何解决我的问题吗?我的剧本是否走在了正确的轨道上?

【问题讨论】:

  • 您正在替换 exp1.sub 行中的整个文本,请尝试仅替换该行。例如text1 = exp1.sub('&lt;lb n="{}"/&gt;'.format(i), line)。然后,您将需要在最后将所有替换的行重新组合在一起。不过你走在正确的轨道上
  • 另外,你应该把这行:exp1 = re.compile(r'&lt;lb n=""/&gt;')放在for循环之前,不需要为每一行编译正则表达式。
  • 您代码中的text1 将继续分配最新行,然后您的函数将只返回最后一行

标签: python regex text-files line-count


【解决方案1】:

您非常接近,这是可以完成工作的代码,希望这会有所帮助:

with open('1.txt') as f1, open('2.txt', 'w') as f2:
    i = 1
    exp1 = re.compile(r'<lb n=""/>')      # look for string
    for line in f1:             
        if '<lb n=""/>' in line:                                        # if string in line
            new_line = exp1.sub('<lb n="{}"/>'.format(i), line) + '\n'           # replace with lb-counter
            i += 1
            f2.write(new_line)
        else:
            f2.write(line)

基本上,只需从一个文件中读取一行并更改 str 并将该行写入新文件。

我在新行末尾添加了“/n”以返回新行。

【讨论】:

    猜你喜欢
    • 2021-12-16
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 2015-10-08
    • 2019-05-14
    • 2021-07-10
    相关资源
    最近更新 更多