繁体   English   中英

如何计算一个字符串的实例并将它们替换为另一个字符串 + 当前计数器?

[英]How to count instances of a string and replace them with another string + the current counter?

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

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

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

目标:我想计算每行字符串<lb n=""/>行并将当前计数器填充到字符串中。

因此,在运行脚本后,示例应如下所示:

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

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

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

代码:

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

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

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

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' 以返回新行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM