繁体   English   中英

如何读取 python 和 output 中的 txt 文件,将每个单词与 txt 文件外的键相关联

[英]How to read a txt file in python and output a dictionary with associating each word with a key outside txt file

我正在阅读一个格式为 txt 的文件

apple, 1234, 156789086654, cat, John
orange, 7654, 8268249252745, dog, Smith
mango, 3467, 8328627427, cow, Alice 

我有一个 key_fields 字典,将键与值类型相关联

key_fields = { fruit : str
               num   : int
               date  : long
               animal : str
               name   : str }

我想从 txt 文件和 key_fields 创建一个最终字典,其中 txt 文件中每一行的每个属性都映射到这样的 key_fields,并具有与 dict key_fields 匹配的适当类型的值字段 -

{ fruit: "apple", num : 1234, date : 156789086654, animal : "cat", name : "John" }
{ fruit: "orange", num: 7654, date: 8268249252745, animal : "dog", name : "Smith"}
{ fruit: "mango", num: 3467, date : 8328627427, animal: "cow", name: "Alice" }

例如,只有一个条目:

line_1 = "apple, 1234, 156789086654, cat, John"

key_fields = { 
    "fruit": str,
    "num": int,
    "date": int,
    "animal": str,
    "name": str
}

result_dict = {key: builder(data) for ((key, builder), data) in zip(key_fields.items(), line_1.split(", "))}

操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM