【问题标题】:Writing dictionaries by Arrays into a csv file and inserting new lines by Array按数组将字典写入 csv 文件并按数组插入新行
【发布时间】: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


    【解决方案1】:

    你可以在没有模块的情况下编写 csvs。

    我更喜欢这样自己做:

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

    【讨论】:

    • 谢谢,但这会将每个字符分成一个新行而不是一个新单词。它也不贴标签。
    • 哦,是的,现在就试试吧。
    猜你喜欢
    • 1970-01-01
    • 2021-03-13
    • 2014-07-13
    • 2018-02-18
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 2018-03-23
    • 1970-01-01
    相关资源
    最近更新 更多