简体   繁体   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

I'm reading a txt file which is of form我正在阅读一个格式为 txt 的文件

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

I have a dictionary of key_fields associating keys with value type我有一个 key_fields 字典,将键与值类型相关联

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

I want to create a final dictionary from txt file and key_fields, where each attribute from each line in txt file is mapped to the key_fields like this, with appropriate type of value fields matching the dict key_fields -我想从 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" }

As an example with just one entry:例如,只有一个条目:

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(", "))}

Playground操场

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

相关问题 如何读取一个txt文件并创建一个字典,每个键都具有python中的值列表? - How to read a txt file and create a dictionary with each key having list of values in python? 如何通过读取.txt文件为每个键创建包含多个“列表”的Python字典? - How to create Python dictionary with multiple 'lists' for each key by reading from .txt file? 如何读取txt文件中的每一行,该文件在python的rar文件中 - How to read each line in txt file which is in rar file in python 如何将.txt文件中的每个单词添加到Python列表中? - How can I add each word in a .txt file to a list in Python? 如何使用邻接表python阅读txt文件并创建字典 - How to read txt file and create dictionary with adjacency list python 如何在 python 中读取 txt 文件数据并转换成嵌套字典 - how to read txt file data and convert into nested dictionary in python Python:如何从 txt 文件而不是 INPUT 中读取每一行 - Python: How to read each line from txt file instead of INPUT 如何读取 python 中每一行的 a.txt 文件? - How to read a .txt file each multiple (various) lines in python? 如何从 txt 文件中读取值是嵌套字典并且嵌套字典的键由我给出的字典? - How to read from a txt file into a dictionary where the value is a nested dictionary and the key of the nested dictionary is given by me? 读取txt文件数据作为字典 - Read txt file data as dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM