我正在尝试修改一个具有基于csv模块的方法的类。
数据是一个简单的三列csv文件,我希望将其转换为一个嵌套的字典列表。
我在这个SO question的帮助下做到了这一点。
然而,我希望能够实现一个更通用的“load_data”方法,我可以使用装饰器来引入方法来输出,以获取加载的csv的两列并作为字典列表输出。
我尝试生成包装器函数和建议的csv_to_dict_dicts方法都被注释掉了。
import csv
class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
"""
def csv_decorator(func):
def func_wrapper(self):
for row in reader:
return dict(self.data[row[0]][row[1]] = row[2] )
return func_wrapper
"""
class CSV:
def __init__(self):
self.data = AutoVivification()
def load_data(self, path):
with open(path, encoding="utf-8") as f:
self.path = path
reader = csv.reader(f)
for row in reader:
self.data[row[0]][row[1]] = row[2]
#@csv_decorator
#def csv_to_dict_dicts(self):
# return self.load_data(path)
c = CSV()
c.load_data(path)更新:
我尝试过使用SO question,如下所示:
def csv_decorator(func):
def func_wrapper(self):
reader = func(self)
for row in reader:
self.data[row[0]][row[1]] = row[2]
return func_wrapper
class CSV:
def __init__(self):
self.data = AutoVivification()
@csv_decorator
def load_data(self, path):
with open(path, encoding="utf-8") as f:
self.path = path
reader = csv.reader(f)
return reader但是,我收到以下错误:
TypeError: func_wrapper() takes 1 positional argument but 2 were given发布于 2017-11-23 20:49:53
在上面贡献者的指导下,我得到了一些可以工作的代码。
def csv_decorator(func):
def func_wrapper(self, path):
reader = func(self, path)
for row in reader:
self.data[row[0]][row[1]] = row[2]
return func_wrapper
class CSV:
def __init__(self):
self.data = AutoVivification()
@csv_decorator
def load_data(self, path):
f = open(path, encoding="utf-8")
self.path = path
reader = csv.reader(f)
return readerhttps://stackoverflow.com/questions/47454903
复制相似问题