首先,因为我以前被一个有电的人烫伤过,所以这个问题不是家庭作业。在
总之,我有一个文本文件,如下所示:
####
# File section 1
####
1.0 abc Description1
6.5 def Description2
1.0 2.0 3.0 ghi Description3
11 jkl Description
####
# File section 2
####
1.0 abc Description1
12.5 def Description2
1.0 2.0 3.0 ghi Description3
11 jkl Description
#### End file
我想替换两行中的字符串“1.0”:
^{pr2}$但是,不是行中的“1.0”字符串:
1.0 2.0 3.0 ghi Description3
我使用的当前代码是:
with open('sample_file.txt','r') as file:
filedata = file.read()
filedata = filedata.replace('1.0','2.0')
with open('sample_file.txt','w') as file:
file.write(filedata)
但是结果是所有出现的“1.0”都会被替换。然后我要回到文件中,纠正错误。我想要得到的结果文件是:
####
# File section 1
####
2.0 abc Description1
6.5 def Description2
1.0 2.0 3.0 ghi Description3
11 jkl Description
####
# File section 2
####
2.0 abc Description1
12.5 def Description2
1.0 2.0 3.0 ghi Description3
11 jkl Description
#### End file
我怎么能得到那个?我找不到解决这类问题的范例。谢谢你们的帮助。在
编辑:我的错误是没有澄清,但我要替换的字符串并不总是“1.0”,也不总是3个字符长。例如可以是“-12.3”。我想让代码尽可能通用。在
我还尝试使用rsplit将空格作为分隔符来隔离第一个字符串,但这似乎不适用于文件写入。在
=========================
编辑2:我找到了一个方法,虽然这似乎是一个相当全面的方法:
with open('sample_file.txt','r') as file:
filedata = file.readlines()
for line in filedata:
if 'abc' in line:
oriline = line
newline = line.replace(str(spk),str(newspk))
with open('sample_file.txt','r') as file:
filedata = file.read()
filedata = filedata.replace(str(oriline),str(newline))
with open('sample_file.txt','w') as file:
file.write(filedata)
基本上,它将打开文件,逐行读取包含我想要的特定字符串的整行,然后将其存储到内存中。然后再次打开文件,读取所有内容,然后替换整个字符串。然后打开文件,并写入该文件。在
它做了我想要的,但是有没有一种方法可以简化代码呢?在
就用吧
与上述快捷方式不同,您可以先定义一个空列表来尝试更通用的情况:
li = []
然后使用下面的代码(考虑到字符串
^{pr2}$abc
和上面的例子一样是固定的):正如我在评论中提到的,您可以使用regular expressions来匹配您要查找的模式。您可以在模式中指定组(使用
(
…)
或(?P<
name…)
)来标识模式的部分,并专门替换或重用这些部分。在这样的方法应该有效:
不使用正则表达式的另一种(未经测试)方法:
^{pr2}$请注意,这与正则表达式(RegularExpression,RE)方法不完全相同(显著的区别是它将接受任何浮点数作为第一个标记(例如
1e-10
),并且在执行替换后它不会保留空格),但是如果您不熟悉REs,则可能会更容易理解相关问题 更多 >
编程相关推荐