在文件中替换字符串为新的字符串

4

我有一个字符串列表保存在文本文件中,其中包括morning,night,sun,moon。我的目标是将其中一个字符串替换为另一个字符串。例如,我输入morning并将其替换为afternoon。但是,当该字符串明显存在于列表中时,我会收到错误消息“builtins.ValueError: list.remove(x): x not in list”。

def main():
    x = input("Enter a file name: ")
    file = open(x , "r+")
    y = input("Enter the string you want to replace: ")
    z = input("Enter the string you to replace it with: ")
    list = file.readlines()
    list.remove(y)
    list.append(z)
    file.write(list)
    print(file.read())

main()

如果有更好的方法以另一种方式实现相同的结果,请让我知道。感谢您的帮助!


你是说直接在原文件上进行编辑而不创建另一个文件吗? - Chiheb Nexus
3
首先,请勿将您的变量命名为list,因为list()是Python内置函数。其次,您列表中的字符串末尾有换行符\n。在尝试remove操作之前,应将其去除。 - DYZ
3个回答

5
以下是一些想法:
  • str.replace() 函数是替换字符串最简单的方法,使用 s.replace(y, z)

  • re.sub() 函数可让您搜索模式并替换为字符串: re.sub(y, z, s)

  • fileinput 模块将允许您进行原地修改。

以下是其中一种实现方式:
import fileinput
import re

with fileinput.input(files=('file1.txt', 'file2.txt'), inplace=True) as f:
    for line in f:
        print( re.sub(y, z, line) )

这里还有一个想法:

  • 不要逐行处理,而是把整个文件读入为一个字符串,修复它,然后再写回去。

例如:

import re

with open(filename) as f:
    s = f.read()
with open(filename, 'w') as f:
    s = re.sub(y, z, s)
    f.write(s)

0
假设您的文本保存在src.txt中:
morning
night
sun
moon

在Windows中,您可以使用此批处理脚本,保存为replace.bat:

@echo off
setlocal enabledelayedexpansion
set filename=%1
set oldstr=%2
set newstr=%3

for /f "usebackq" %%i in (%filename%) do (
    set str=%%i
    set replace=!str:%oldstr%=%newstr%!
    echo !replace!
)

使用方法:

replace.bat src.txt morning afternoon > newsrc.txt

或者使用 grepWin

使用 sedgawk 可能更简单。

sed -i "s/morning/afternoon/g" src.txt

-1

也许您正在寻找 Python replace() 方法?

str = file.readlines()
str = str.replace(y, z) #this will replace substring y with z within the parent String str

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接