簡體   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