温馨提示×

python怎么替换文本文件单词

小亿
106
2024-01-16 20:38:52
栏目: 编程语言

要替换文本文件中的单词,可以使用Python的文件读写操作和字符串替换函数。

下面是一个示例代码,演示了如何替换文本文件中的单词:

def replace_word(file_path, old_word, new_word):
    # 打开文件并读取内容
    with open(file_path, 'r') as file:
        content = file.read()

    # 使用replace函数替换单词
    new_content = content.replace(old_word, new_word)

    # 将替换后的内容写回文件
    with open(file_path, 'w') as file:
        file.write(new_content)

# 替换test.txt文件中的"old"为"new"
replace_word('test.txt', 'old', 'new')

在上面的代码中,replace_word函数接受三个参数:文件路径(file_path)、要替换的单词(old_word)和替换后的单词(new_word)。

函数首先使用open函数打开文件,并使用read方法读取文件内容到变量content中。

接下来,使用字符串的replace方法替换content中的单词,并将结果保存到变量new_content中。

最后,使用open函数再次打开文件,并使用write方法将new_content写入文件中,实现替换操作。

在示例代码中,我们将文件名设置为test.txt,要替换的单词设置为old,替换后的单词设置为new。你可以根据实际需求修改这些参数。

0