首页 > 解决方案 > 使用文件中的密钥对替换列表中的值

问题描述

我有一个带有去识别 ID 的文件,如下所示:

IDs.txt

a   Michael
b   Elizabeth
c   Pierre
d   Nicholas

我有一个结果文件(假设它们是权重): results.txt

a   b   c   d
181   150   168   190

如何用IDs.txtpython 文件中的关联值替换结果文件的第一行?

到目前为止,我有

dic = {}

with open("metadata.txt","r") as fp:
    for line in fp:
        key_val = line.strip().split()
        dic[key_val[0]] = key_val[1]

resp = open("res.txt","r")

res_lis = resp.readline().split()
res_lis2 = []
for i in res_lis:
    res_lis2 = dic[res_lis]

如何将我的第一行中的这些键值替换results.txt为我的字典键对中的关联值?

预期结果将是:

Michael   Elizabeth   Pierre   Nicholas
181   150   168   190

标签: pythondictionary

解决方案


dic = {}

# Read IDs.txt and store the required dictionary in dic
with open("IDs.txt","r") as fp:
    for line in fp:
        key_val = line.strip().split()
        dic[key_val[0]] = key_val[1]


# read the lines in result.txt file to res_lis,   
with open("result.txt","r") as resp:

    res_lis = resp.read().split("\n")

    # Store modified first line in res_lis2,
    res_lis2 = []
    for char in res_lis[0]:
        if char in dic.keys():
            res_lis2.append(dic[char])
        else:
            res_lis2.append(char)
    
    # replace first line of res_lis with modified line
    res_lis[0] = "".join(res_lis2)


# Open result.txt file as write the text with modified first line
with open("result.txt","w") as resp: 

    resp.write("\n".join(res_lis))

正如@martineau 还建议的那样,这会用适当的替换来重写文件


推荐阅读