【问题标题】:Convert excel or csv to list or dictionary, or word doc to list in python将 excel 或 csv 转换为列表或字典,或将 word doc 转换为 python 中的列表
【发布时间】:2021-01-06 10:04:18
【问题描述】:

我希望我的最终结果是像下面这样的字典。

mydict = {0:'term1', 1:'term2',...'159:'term160'}

我有一个包含单列数据的 csv,在该列的单行的每个单元格中都有几个单词。

到目前为止,我在这里找到的任何建议都没有帮助。我最接近的是一个公式创建了多个有序字典,这些字典从我的单列创建了如下字典:

{['term1'], ['term2']}
{['term1'], ['term3']}
{['term1'], ['term4']}

所以,我不这样做,而是想从列中创建一个列表。当使用下面的代码时,而不是得到类似['term1', 'term2', 'term3',...'term160'] 的东西,我收到了[['term1'],['term2'],...['term160']],当通过my_dict = dict.fromkeys(my_list_numbers, my_list_terms)my_list2 = list(range(0, 160)) 结合时,打印出与整个匹配范围内的每个数字的字典[['term1'],['term2'],...['term160']]

import csv

with open('filename.csv') as file:
    reader = csv.reader(file)
    data = list(reader)

print(data)

我只想要一个字典或一个可以变成字典的字符串列表,这样我就不必输入多个字典,每个字典都有 100 多对。我已经在谷歌上搜索和试验了一个多小时。我对代码比较陌生,但我觉得从 excel、csv、word 或文本文档中提取字符串列表应该不难。或者只是从我粘贴到单元格中的列表中格式化,甚至。

任何帮助将不胜感激。

【问题讨论】:

  • 请提供样本 csv 数据和相应的所需输出数据。谢谢。
  • @Argileon,假设您的数据是单列并且您将输出视为列表,请尝试以下{idx:value[0] for idx, value in enumerate(data)}

标签: python excel list csv dictionary


【解决方案1】:

假设文件 temp.csv 中的数据如下:

this_is_r1
this_is_r2
this_is_r3
this_is_r4

您可以将代码编写为:

import os
os.chdir("/home/username/Downloads")

res= dict()

with open("temp.csv", "r") as f:
    for k,x in enumerate(f):
        res[k] = x.replace("\n","")

print(res)

输出是:

{0: 'this_is_r1', 1: 'this_is_r2', 2: 'this_is_r3', 3: 'this_is_r4', 4: 'this_is_r5', 5: 'this_is_r6'}

根据 Miguel Trejo 的建议,您还可以将字典理解用作:

with open("temp.csv", "r") as f:
    res={k:x.replace("\n","") for k,x in enumerate(f)}

print(res)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-11
    • 2011-08-30
    • 2020-01-03
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 2014-04-24
    相关资源
    最近更新 更多