2017-04-09 130 views
2

我有一个文本文件中的字符串列表。琴弦是早晨,晚上,太阳,月亮。我想要做的是用另一个字符串替换这些字符串中的一个。例如,我会在上午输入以删除并在下午进行替换。当字符串清楚地出现在列表中时,出现错误“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() 

如果有更好的方法来达到相同的效果,那就让我知道。谢谢您的帮助!

+0

你的意思是编辑文件而不创建另一个? –

+2

首先,请不要调用变量'list',因为list()是一个内置函数。其次,你的'list'中的字符串最后有'\ n''换行符。在尝试“移除”之前,您应该将它们剥离。 – DyZ

回答

1

这里有一些想法:

  • 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) 
-1

也许你正在寻找一个为Python replace()方法?

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

假设你的TXT保存在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