我有一个如下所示的文本文件:
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.sub
和 0([\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/