如何使用python有条件地替换文本文件中的子字符串
我有一个如下所示的文本文件:如何使用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 f1 = open('Text1.txt','r') f2 = open
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
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()
我的任务是使用Python将所有标签0(即test_xxxxx.png之后的0,而不是像test_00000.png这样的图像名称中的0)替换为1。我的代码如下所示:
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
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()
但是,这段代码提供的输出与原始文件完全相同。我在这里做错了什么?我该如何修复它?我建议只看这行的末尾会更容易:
with open('file1', 'r') as f1, open('file2', 'w') as f2:
for line in f1.readlines():
line = line.strip()
if line.endswith(' 0'):
line = line[:-2] + ' 1'
f2.write(line + '\n')
如果可以接受输出文件可以有1个空间,则可以使用pandas来读取:
import pandas as pd
data = '''\
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'''
file = pd.compat.StringIO(data) # replace with "path/to/file"
df = pd.read_csv(file, sep='\s+', header=None).replace(0,1)
df.to_csv('out.csv', sep=' ', header=False, index=False)
将
re.sub
与以下各项一起使用:
正则表达式解释:
0 # matches 0
( # matching group 1
[\n$] # matches newline or end of line
| # OR
\Z # Matches EOF
) # End of matching group 1
将
替换为1\1
(将1替换为0,并保持适当的下线字符)
out.txt
该行不以空格结尾。文件是否由两个空格分隔?原始文本文件每行包含一个.png。因此,每一行看起来都像“test_xxxxx.png 0”,模式只是重复snope。不是只读的。。。
line
的原始值是不可变的,名称本身可以更改为指向其他内容。这段代码已经过测试并且有效。@SashaTsukanov,无需道歉。我们都在这里学习和帮助。要求澄清。要么你学点什么,要么我学点什么。在这两种情况下,好事都会发生。干杯。下面是一个问题:您能解释\1在代码中的含义吗?@chriszIn在正则表达式中,匹配组捕获匹配组1中每一行的特定行尾。在替换中使用\1意味着将恢复正确的行尾。因此,基本上\1指的是匹配组1中捕获的内容。如果不将0替换为1,而是将它们替换为数组中的元素,如arr[I],我该怎么办?除了在for循环中将“r'1\1'”替换为“arr[I]”之外,我使用了类似的语法,但是得到了一个可以替换为lambda函数的错误。有一些例子你可以用谷歌搜索。如果你给我一个简单的例子,我可以在今晚晚些时候更新我的答案