2017-04-09 121 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