在Python中替换文件中的特定字符串

2024-09-30 00:38:04 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,因为我以前被一个有电的人烫伤过,所以这个问题不是家庭作业。在

总之,我有一个文本文件,如下所示:

####
# 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)

基本上,它将打开文件,逐行读取包含我想要的特定字符串的整行,然后将其存储到内存中。然后再次打开文件,读取所有内容,然后替换整个字符串。然后打开文件,并写入该文件。在

它做了我想要的,但是有没有一种方法可以简化代码呢?在


Tags: 文件sample字符串txtaswithsectionopen
2条回答

就用吧

with open('sample_file.txt','r') as file:
    filedata = file.read()
    filedata = filedata.replace('1.0   abc','2.0   abc')
with open('sample_file.txt','w') as file:
    file.write(filedata)

与上述快捷方式不同,您可以先定义一个空列表来尝试更通用的情况:

li = []

然后使用下面的代码(考虑到字符串abc和上面的例子一样是固定的):

^{pr2}$

正如我在评论中提到的,您可以使用regular expressions来匹配您要查找的模式。您可以在模式中指定(使用()(?P<name))来标识模式的部分,并专门替换或重用这些部分。在

这样的方法应该有效:

import re

pattern = (r'^' # The beginning of a line.
           # Match something that looks like a number:
           r'-?'        # 1. Optional: a negative sign.
           r'\d+'       # 2. One or more digits.
           r'([.]\d+)?' # 3. Optional: a decimal point followed by one
                        #    or more digits.
           # The rest of the line:
           r'(?P<rest>'
             r'\s+' # 1. One or more spaces.
             r'abc' # 2. "abc"
             r'\s+' # 3. One or more spaces.
             r'.*'  # 4. Everything remaining.
           r')' 
           r'$') # The end of a line.

# Replace the above pattern with "2.0" followed by whatever we identified
# as "the rest of the line".
replacement = '2.0\g<rest>'

with open('sample_file.txt','r') as file:
    filedata = file.read()

    # re.MULTILINE is needed to treat lines separately.
    filedata = re.sub(pattern, replacement, filedata, flags=re.MULTILINE)
with open('sample_file.txt','w') as file:
    file.write(filedata)

不使用正则表达式的另一种(未经测试)方法:

^{pr2}$

请注意,这与正则表达式(RegularExpression,RE)方法不完全相同(显著的区别是它将接受任何浮点数作为第一个标记(例如1e-10),并且在执行替换后它不会保留空格),但是如果您不熟悉REs,则可能会更容易理解

相关问题 更多 >

    热门问题