首页 > 解决方案 > 循环遍历字典以替换文本文件中的多个值

问题描述

我正在尝试更改文本文件中的几个十六进制值。我制作了一个 CSV,其中一列中包含原始值,另一列中包含新值。

我的目标是编写一个简单的 Python 脚本,根据第一列在文本文件中查找旧值,并在第二列中用新值替换它们。

我正在尝试使用字典来促进replace()我通过循环通过 CSV 创建的这一点。构建它很容易,但是用它来执行 areplace()并没有成功。当我在脚本运行后打印出值时,我仍然看到原始值。

我已经尝试使用read()和执行对整个文件的更改来读取文本文件,就像上面一样。

import csv

filename = "origin.txt"
csv_file = 'replacements.csv'
conversion_dict = {}

# Create conversion dictionary
with open(csv_file, "r") as replace:
    reader = csv.reader(replace, delimiter=',')
    for rows in reader:
        conversion_dict.update({rows[0]:rows[1]})

#Replace values on text files based on conversion dict
with open(filename, "r") as fileobject:
    txt = str(fileobject.read())
    for keys, values, in conversion_dict.items():
        new_text = txt.replace(keys, values)

我还尝试将更新后的文本添加到列表中:

#Replace values on text files based on conversion dict
with open(filename, "r") as fileobject:
    txt = str(fileobject.read())
    for keys, values, in conversion_dict.items():
        new_text.append(txt.replace(keys, values))

然后,我尝试使用readlines()一次一行用新值替换旧值:

# Replace values on text files based on conversion dict
with open(filename, "r") as reader:
    reader.readlines()
    type(reader)
    for line in reader:
        print(line)
        for keys, values, in conversion_dict.items():
            new_text.append(txt.replace(keys, values))

在进行故障排除时,我进行了测试以查看我的 dict 中的键与文件中的文本之间是否有任何匹配:

for keys, values, in conversion_dict.items():
    if keys in txt:
        print("match")
    else:
        print("no match")

除了第一行,我的输出match在每一行都返回。我想通过一些修剪或我可以解决的问题。但是,这证明有匹配项,所以我的代码肯定有其他问题。

任何帮助表示赞赏。

标签: python

解决方案


起源.txt:

oldVal9000,oldVal1,oldVal2,oldVal3,oldVal69

测试.csv:

oldVal1,newVal1
oldVal2,newVal2
oldVal3,newVal3
oldVal4,newVal4
import csv

filename = "origin.txt"
csv_file = 'test.csv'
conversion_dict = {}

with open(csv_file, "r") as replace:
    reader = csv.reader(replace, delimiter=',')
    for rows in reader:
        conversion_dict.update({rows[0]:rows[1]})

f = open(filename,'r')
txt = str(f.read())
f.close()

txt= txt.split(',')         #not sure what your origin.txt actually looks like, assuming comma seperated values
for i in range(len(txt)):
    if txt[i] in conversion_dict:
        txt[i] = conversion_dict[txt[i]]
        
with open(filename, "w") as outfile:
    outfile.write(",".join(txt))

修改 origin.txt:

oldVal9000,newVal4,newVal1,newVal3,oldVal69


推荐阅读