आप एक जनरेटर समारोह निम्नलिखित की तरह उपयोग कर सकते हैं:
def func():
list_of_keys = ['S_Length','S_Width','P_Length','P_Width','Predicate']
with open('example.txt') as f:
for line in f:
yield dict(zip(list_of_keys,line.strip().split(',')))
print(list(func()))
[{'P_Width': '0.2', 'S_Length': '2.1', 'Predicate': 'Iris', 'S_Width': '3.5', 'P_Length': '1.4'}, {'P_Width': '0.2', 'S_Length': '4.9', 'Predicate': 'Ilia', 'S_Width': '3.0', 'P_Length': '1.4'}, {'P_Width': '0.2', 'S_Length': '3.7', 'Predicate': 'Iridium', 'S_Width': '3.2', 'P_Length': '1.3'}]
आप लाइन द्वारा फ़ाइल लाइन पढ़ सकते हैं और लाइनों अलग हो गए, तो जोड़े बनाने zip
फ़ंक्शन का उपयोग करके कुंजी और मानों का उपयोग करें और फिर उन्हें एक शब्दकोश में परिवर्तित करें।
ध्यान दें कि चूंकि फ़ाइल ऑब्जेक्ट एक पुनरावर्तक है, तो आप अपनी फ़ाइल ऑब्जेक्ट पर फिर से सक्रिय हो सकते हैं और अपनी फ़ाइल खोलने के लिए with
कथन का उपयोग कर सकते हैं जो ब्लॉक के अंत में फ़ाइल को बंद कर देगा।
एक और वैकल्पिक और अधिक pythonic जिस तरह से आप भी csv
मॉड्यूल का उपयोग कर सकते हैं अपने पाठ फ़ाइल को पढ़ने के लिए के रूप में:
import csv
def func():
list_of_keys = ['S_Length','S_Width','P_Length','P_Width','Predicate']
with open('example.txt') as f:
spamreader = csv.reader(f, delimiter=',')
return [dict(zip(list_of_keys,row)) for row in spamreader]
print func()
यहाँ csv.reader
के बाद से एक सीमांकक तर्क स्वीकार करता है और एक इटरेटर आप डॉन 'में अलग अपने लाइनों की पूरी रिटर्न टी को अपनी फाइल पर लूप करने की जरूरत है और इसे मैन्युअल रूप से विभाजित करें।
और तुम आपको दोनों ही मामलों में collections.OrderedDict
उपयोग कर सकते हैं की रक्षा करना चाहते हैं:
from collections import OrderedDict
import csv
def func():
list_of_keys = ['S_Length','S_Width','P_Length','P_Width','Predicate']
with open('example.txt') as f:
spamreader = csv.reader(f, delimiter=',')
return [OrderedDict(zip(list_of_keys,row)) for row in spamreader]
print func()
[OrderedDict([('S_Length', '2.1'), ('S_Width', '3.5'), ('P_Length', '1.4'), ('P_Width', '0.2'), ('Predicate', 'Iris')]), OrderedDict([('S_Length', '4.9'), ('S_Width', '3.0'), ('P_Length', '1.4'), ('P_Width', '0.2'), ('Predicate', 'Ilia')]), OrderedDict([('S_Length', '3.7'), ('S_Width', '3.2'), ('P_Length', '1.3'), ('P_Width', '0.2'), ('Predicate', 'Iridium')])]
एक ओपी जो का उपयोग कर एक फ़ाइल पर iterates के लिए 'रेंज (लेन()) 'इसके लिए _a बिट more_ स्पष्टीकरण की आवश्यकता है। – bereal
@bereal वास्तव में, मैंने अभी जोड़ा। – Kasramvd