【发布时间】:2020-08-21 19:26:09
【问题描述】:
我正在尝试将新行插入到我正在写入此数据的 csv 文件中。数据是
data = [[{'Hi': 'O'}, {'mr': 'O'}, {'you': 'O'}, {'president': 'O'}, {'USA': 'Country'}, {'for': 'O'}, {'answering': 'O'}, {'football': 'O'}, {'questions': 'O'}, {'music': 'JAZZ'}], [{'Hi': 'O'}, {'You': 'O'}, {'have': 'O'}, {'granted': 'STATE'}, {'purchased': 'O'}, {'GHC3': 'O'}, {'Bundle': 'O'} {'248803151': 'O'}]]
这是我的代码,但我不确定如何重新编码以适应数据中每个数组的新行。
def convert_to_biolu(dico, biolu_list = defaultdict(list)): #dico here is output_data
for dict_item in dico: # you can list as many input dicts as you want
for key, value in dict_item.items():
if value not in biolu_list[key]:
biolu_list[key].append(value)
return biolu_list
def save_to_file(path, data_):
data_ = [convert_to_biolu(item) for item in data][-1]
with open(path, 'w', newline='') as file:
fieldnames = ['word', 'label']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
for key, val in data_.items():
writer.writerow({'word': key, 'label': " ".join(val)})
【问题讨论】:
标签: python python-3.x algorithm csv data-structures