不使用內置的方式,一種是任務一樣,這是不是一個好主意,因爲你的事情複雜了許多帶話。我假設你不想使用正則表達式操作模塊're'要麼...所以找到我的答案在下面。這可以寫少線,但這種方式更具有可讀性:
def replace_string(string1, string2, file1, file2):
with open(file1, 'r') as first_file:
my_lines = []
for line in first_file.readlines():
if string1 in line:
for word in line.split(string1):
if word != string1:
if (word and '\n' not in word):
new_word = word+string2
else:
new_word = word
my_lines.append(new_word)
else:
my_lines.append(line)
with open(file2, 'w') as second_file:
for item in my_lines:
second_file.write(item)
比方說,你有「first_file.txt」,看起來像這樣:
This is my first line. It contains the words: cat, dog, fish, cat.
This is the second line. cat. ‘cat’ is a pet
This is the third line. cat...cat cat.
You have hopefully replaced all occurrences of *cat*cat
而且要替換字符串「 cat'與'new_cat'並保存到'second_file.txt'文件中。您不需要創建second_file.txt,它只會在您運行代碼的相同位置創建。
replace_string('cat', 'new_cat', 'first_file.txt', 'second_file.txt')
你的第二個文件將是這樣的:
This is my first line. It contains the words: new_cat, dog, fish, new_cat.
This is the second line. new_cat. ‘new_cat’ is a pet
This is the third line. new_cat...new_cat new_cat.
You have hopefully replaced all occurrences of *new_cat*new_cat
當然,這是不完美的。如果你在文件'catcat'中有一個單詞會發生什麼......你想忽略它嗎?或者你想把它變成'new_catnew_cat'?這個代碼將它變成'new_cat'只...所以這裏有另一個條件來檢查,等等...
'在fin1中的單詞:'逐行讀取文件,而不是逐字讀取 –
How我可以讓它逐字閱讀嗎? – user1691278
而不是你有什麼,我可以推薦'除了例外作爲e:sys.exit(「錯誤的東西:」+ str(e))''。這樣你可以真正看到具體發生了什麼問題。在實踐中,你應該捕獲特定的錯誤,比如'OSError'或者'IOError',這樣其他意外的錯誤,比如'AttributeError'或者'TypeError',不會神祕地讓你陷入瘋狂的追逐。 – SethMMorton