共計 722 個字符,預(yù)計需要花費 2 分鐘才能閱讀完成。
要替換文本文件中的單詞,可以使用 Python 的文件讀寫操作和字符串替換函數(shù)。
下面是一個示例代碼,演示了如何替換文本文件中的單詞:
def replace_word(file_path, old_word, new_word):
# 打開文件并讀取內(nèi)容
with open(file_path, 'r') as file:
content = file.read()
# 使用 replace 函數(shù)替換單詞
new_content = content.replace(old_word, new_word)
# 將替換后的內(nèi)容寫回文件
with open(file_path, 'w') as file:
file.write(new_content)
# 替換 test.txt 文件中的 "old" 為 "new"
replace_word('test.txt', 'old', 'new')
在上面的代碼中,replace_word
函數(shù)接受三個參數(shù):文件路徑(file_path
)、要替換的單詞(old_word
)和替換后的單詞(new_word
)。
函數(shù)首先使用 open
函數(shù)打開文件,并使用 read
方法讀取文件內(nèi)容到變量 content
中。
接下來,使用字符串的 replace
方法替換 content
中的單詞,并將結(jié)果保存到變量 new_content
中。
最后,使用 open
函數(shù)再次打開文件,并使用 write
方法將 new_content
寫入文件中,實現(xiàn)替換操作。
在示例代碼中,我們將文件名設(shè)置為test.txt
,要替換的單詞設(shè)置為old
,替換后的單詞設(shè)置為new
。你可以根據(jù)實際需求修改這些參數(shù)。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完