使用字典搜索和替换文件

search and replace using dictionary on files

我正在尝试编写一个程序来从文件中读取输入 a.txt

Hi this is nick, I am male and I am 30 years old.

并替换人的姓名、年龄和性别并写入新文件b.txt。 下面是我的尝试。

orig_file=open("a.txt","r") # file handle 
new_file=open("b.txt","w")    # new file handle
temp_buffer=orig_file.read()
lookup_dict={"nick":"andrea", "male":"female", "30":"20"}

for line in temp_buffer:
    for word in lookup_dict:
        line= line.replace(word, lookup_dict[word])
        new_file.write(line)

我对 b.txt 的预期结果是

Hi this is andrea, I am female and I am 20 years old.

观察到的输出(b.txt)

HHHiii   ttthhhiiisss   iiisss   nnniiiccckkk,,,   III   aaammm   mmmaaallleee   aaannnddd   III   aaammm   333000   yyyeeeaaarrrsss   ooolllddd...

谁能解释一下我做错了什么并纠正我。

使用 readlines 而不是 read 并在文件上手动调用 close(),因为您没有使用 with :

orig_file = open("a.txt", "r")  # file handle
new_file = open("b.txt", "w")  # new file handle
temp_buffer = orig_file.readlines()
orig_file.close()
lookup_dict = {"nick": "andrea", "male": "female", "30": "20"}
for line in temp_buffer:
    for word in lookup_dict:
        line = line.replace(word, lookup_dict[word])
    new_file.write(line)
new_file.close()

b.txt:

Hi this is andrea, I am female and I am 20 years old.