[英]Convert Tabular Data with “X” columns into dictionary without pandas or csv packages
我正在准備測試,其中一個主題是解析表格數據而不使用csv / panda包。
問題是獲取具有任意數量列的數據並將其轉換為字典。 分隔符可以是空格,冒號或逗號。 例如,這里有一些逗號作為分隔符的數據 -
person,age,nationality,language, education
Jack,18,Canadian,English, bs
Rahul,25,Indian,Hindi, ms
Mark,50,American,English, phd
Kyou, 21, Japanese, English, bs
這應該轉換成這樣的字典格式 -
{'person': ['Jack', 'Rahul', 'Mark', 'Kyou'], 'age': ['18', '25', '50', '21'], 'education': ['doc', 'eng', 'llb', 'ca'], 'language': ['English', 'Hindi', 'English', 'English'
], 'nationality': ['Canadian', 'Indian', 'American', 'Japanese']}
列可以在不同文件之間變化。 我的程序應該靈活處理這種變化。 例如,在下一個文件中可能會有另一個標題為“性別”的列。
我能夠讓這個工作,但覺得我的代碼非常“笨重”。 它有效,但我想做更多“pythonic”的事情。
from collections import OrderedDict
def parse_data(myfile):
# initialize myd as an ordered dictionary
myd = OrderedDict()
# open file with data
with open (myfile, "r") as f:
# use readlines to store tabular data in list format
data = f.readlines()
# use the first row to initialize the ordered dictionary keys
for item in data[0].split(','):
myd[item.strip()] = [] # initializing dict keys with column names
# variable use to access different column values in remaining rows
i = 0
# access each key in the ordered dict
for key in myd:
'''Tabular data starting from line # 1 is accessed and
split on the "," delimiter. The variable "i" is used to access
each column incrementally. Ordered dict format of myd ensures
columns are paired appropriately'''
myd[key] = [ item.split(',')[i].strip() for item in data[1:]]
i += 1
print dict(myd)
# my-input.txt
parse_data("my-input.txt")
您能否建議我如何使我的代碼“更清潔”?
這是一種更加pythonic的方式來解決這個問題。
def parse(file):
with open(file, 'r') as f:
headings = f.readline().strip().split(',')
values = [l.strip().split(',') for l in f]
output_dict = {h: v for h, v in zip(headings, [*zip(*values)])}
return output_dict
print(parse('test.csv'))
首先,將文件中的第一行作為標題用於字典中的鍵(這將打破重復的標題)
然后,使用列表推導將所有剩余值讀入字符串列表的列表中。
最后,通過使用轉置(即[*zip(*values))]
表示的標題列表來編譯字典 - 如果您願意使用numpy,則可以將其替換為numpy.array(values).T
for例)
稍微好一點的版本
def parse_data(myfile):
# read lines and strip out extra whitespaces and newline characters
lines = [line.strip() for line in open(myfile,"r").readlines()]
dict = {} # initialize our dict variable
# start loop from second line
for x in range(1,len(lines)):
# for each line split values and store them in dict[col]
for y in range(len(lines[0].split(","))):
# if col is not present in dict create new column and initialize it with a list
if lines[0].split(",")[y] not in dict:
dict[lines[0].split(",")[y]] = []
# store the corresponding column value to the dict
dict[lines[0].split(",")[y]].append(lines[x].split(",")[y])
parse_data("my-input.txt")
在這里看到它。
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.