【问题标题】:search and replace using dictionary on files使用字典搜索和替换文件
【发布时间】:2022-01-21 15:40:28
【问题描述】:

我正在尝试编写一个程序来从文件 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...

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

【问题讨论】:

  • 你得到什么错误或错误输出?
  • 嗨@match,我已经用观察到的输出更新了这个问题。
  • temp_buffer=orig_file.read() 会将所有字符读入 temp_buffer 但不是行。也许您想做temp_buffer=orig_file.readlines() 然后遍历每一行,目前您遍历每个字符 3 次并打印 3 次。您还希望取消缩进写入行,这样您就不会为您替换的每个单词编写该行。只需在所有单词替换的末尾写下一行
  • 谢谢@ChrisDoyle,现在一切都说得通了

标签: python file dictionary


【解决方案1】:

使用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.

【讨论】:

    猜你喜欢
    • 2020-01-21
    • 2018-11-24
    • 1970-01-01
    • 2020-05-12
    • 2017-11-24
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多