道歉:我是编程新手。老实说,我努力使它工作。我认为我了解问题所在,但不了解如何解决。我在我的代码中的这个论坛上使用了一些已回答的问题,但这还不够。
重点:我有一个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”以返回新行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句