python - 使用文件中的密钥对替换列表中的值
问题描述
我有一个带有去识别 ID 的文件,如下所示:
IDs.txt
a Michael
b Elizabeth
c Pierre
d Nicholas
我有一个结果文件(假设它们是权重):
results.txt
a b c d
181 150 168 190
如何用IDs.txt
python 文件中的关联值替换结果文件的第一行?
到目前为止,我有
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
解决方案
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 还建议的那样,这会用适当的替换来重写文件
推荐阅读
- java - 在 Selenium WebDriver 中使用自定义自动化 ID 的最佳实践是什么
- google-cloud-platform - 基于子域重写谷歌计算实例的端口
- php - 连接运算符问题(点)之前和之后的 PHP PSR 空格
- api - 如何使用 Autodesk Forge API 将上传的 AutoCAD 文件中的元数据提取到 Web 应用程序中?
- python - 如何仅使用python中的if条件将列表的值与函数值进行比较?
- javascript - 在 React 项目中更改 Saga 内部位置的方法
- bash - 如何使用 awk 命令从记录中删除特定字段的前导和尾随空格?
- c# - 有没有办法在不重新启动机器人以使更改采取行动的情况下更改命令前缀?(DSharpPlus)
- php - 为postgresql查询转义数组中的字符串时使用什么php函数
- python - 我如何创建一个包含在应用程序中的 tkinter 应用程序更新程序