python - 如何使用 python 有条件替换文本文件中的子字符串

标签 python

我有一个如下所示的文本文件:

test_00000.png  0
test_00001.png  0
test_00002.png  0
test_00003.png  0
test_00004.png  0
test_00005.png  0
test_00006.png  0
test_00007.png  0
test_00008.png  0
test_00009.png  0
test_00010.png  0

我的任务是使用Python将所有标签0(即test_xxxxx.png后面的0,而不是test_00000.png等图像名称中的0)替换为1。我的代码如下所示:

f1 = open('Text1.txt','r')
f2 = open('Text2.txt','w')
for line in f1:
    for char in line:
        if char==" 0 ":
            f2.write(' 1 ')
        else:
            f2.write(char)
f1.close()
f2.close()

但是,这段代码给出的输出与原始文件完全相同。我在这里做错了什么以及如何解决它?

最佳答案

使用 re.sub0([\n$]|\Z) :

正则表达式解释:

0                     # matches 0
(                     # matching group 1
  [\n$]               # matches newline or end of line
  |                   # OR
  \Z                  # Matches EOF
)                     # End of matching group 1

replace with 1\1(将 1 替换为 0,并保持正确的 EOL 字符)

import re

with open('test.txt') as f, open('out.txt', 'w') as outf:

  data = re.sub(r'0([\n$]|\Z)', r'1\1', f.read())
  outf.write(data)

out.txt

test_00000.png  1
test_00001.png  1
test_00002.png  1
test_00003.png  1
test_00004.png  1
test_00005.png  1
test_00006.png  1
test_00007.png  1
test_00008.png  1
test_00009.png  1
test_00010.png  1

关于python - 如何使用 python 有条件替换文本文件中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50428383/

相关文章:

python - 使用 pandas dtype 作为条件

python - 依赖单元测试

python - 在cross_val_score中,参数cv的使用有何不同?

python - markup.py 如何在标签中使用 ':'

python - 增加数组元素测试的表现力

python - 比较运算符的正则表达式

python - 如何在python中计算百分比

python - 绘制二维数据 : heatmap with different colormaps

python - 在文本小部件中设置光标位置

Python:通过套接字接收数据 - [Errno 11] 资源暂时不可用