简体   繁体   English

通过 Arrays 将字典写入 csv 文件并按数组插入新行

[英]Writing dictionaries by Arrays into a csv file and inserting new lines by Array

I am trying to insert a new line into a csv file that I am writing this data into.我正在尝试将新行插入到我正在写入此数据的 csv 文件中。 The data is数据是

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'}]]

This is the code I have but I am not sure how to re-code it to accommodate the new line per array in the data.这是我拥有的代码,但我不确定如何重新编码以适应数据中每个数组的新行。

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)})

You can write csvs without the module.您可以在没有模块的情况下编写 csvs。

I prefer to do it myself like this:我更喜欢自己这样做:

def write_csv_with_spaces(data, filename):
    with open(FILENAME, 'w+') as file:
        for list in data:
            for dict in list:
                file.write(','.join([str(key) + ',' + str(value) for key,value in dict.items()]) + '\n')
            file.write('\n')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM