python3根据字典对文件关键词进行替换,并用代码展示
时间: 2023-03-06 20:55:33 浏览: 133
python入小课_代码实现30个.pdf
Python3可以使用字典来替换文件中的关键词,代码如下:f = open("file.txt", 'r')
lines = f.readlines()
new_lines = []dictionary = {
'old_word1': 'new_word1',
'old_word2': 'new_word2',
# etc
}for line in lines:
new_line = line
for old_word, new_word in dictionary.items():
new_line = new_line.replace(old_word, new_word)
new_lines.append(new_line)f.close()f = open("file.txt", 'w')
for line in new_lines:
f.write(line)
f.close()
阅读全文