Python将带有逗号分隔符的.csv文件转换为字典

2024-04-20 03:08:12 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我已经尝试解决这个问题很长一段时间了,并做了一些研究,试图找出为什么我的代码不能工作,但我根本无法让字典以所有正确的方式打印出来键:值对我需要。你知道吗

故事是这样的。我正在读一个.csv文件,其中第一列是文本缩写,第二列是完整的英文意思。现在我尝试了多种方法来打开这个文件,读取它,然后将它存储到我们创建的字典中。我的问题是,文件被读取,当我打印分离的部分时(我相信它会穿过整个文件,但我不知道,因为它确实在第1007行被切断,但会穿过4600行)。问题是当我现在想把所有的东西都放进去键:值对在字典里。唯一存储的是文件中的第一行。你知道吗

代码如下:

def createDictionary(filename):
    f = open(filename, 'r')
    dic = {}
    for line in f:
        #line = line.strip()
        data = line.split(',')
        print data
        dic[data[0]] = data[1]
        print dic

我认为问题是:

    print dic

因为它是在循环中打印的,但是因为它是在循环中的,所以每次它经过一次又一次的打印就应该打印。我对自己做错了什么感到困惑。我尝试使用的其他方法是json,但是我不太了解如何使用它,然后我也阅读了csv模块,但是我认为我们的教授不希望我们使用它,所以我希望有人能发现我的错误。提前谢谢!!!你知道吗

编辑

这是我程序的输出

going to be late\rg2cu', 'glad to see you\rg2e', 'got to eat\rg2g', 'got to go\rg2g2tb', 'got to go to the bathroom\rg2g2w', 'got to go to work\rg2g4aw', 'got to go for a while\rg2gb', 'got to go bye\rg2gb2wn', 'got to go back to work now\rg2ge', 'got to go eat\rg2gn', 'got to go now\rg2gp', 'got to go pee\rg2gpc', 'got 2 go parents coming\rg2gpp', 'got to go pee pee\rg2gs', 'got to go sorry\rg2k', 'good to know\rg2p', 'got to pee\rg2t2s', 'got to talk to someone\rg4u', 'good for you\rg4y', 'good for you\rg8', 'gate\rg9', 'good night\rga', 'go ahead\rgaalma', 'go away and leave me alone\rgafi', 'get away from it\rgafm', 'Get away from me\rgagp', 'go and get pissed\rgaj'

它会持续一段时间直到文件的结尾,然后它会打印出我得到这个的整个字典

   {'$$': 'money\r/.'}

还有一个

none

编辑2

以下是完整代码:

def createDictionary(filename):
    f = open(filename, 'r')
    dic = {}
    for line in f:
        line = line.strip()
        data = line.split(',')
        print data
        dic[data[0]] = data[1]
        print dic

if __name__ == "__main__":
    x = createDictionary("textToEnglish.csv")
    print x

编辑3

这是我想编成词典的文件

https://1drv.ms/u/s!AqnudQBXpxTGiC9vQEopu1dOciIS


Tags: 文件csvto代码gofordata字典
2条回答

只需在函数中添加return。此外,由于csv的第一列中存在重复的值,您将看到字典长度与csv行不同。字典键必须是唯一的,所以当一个重用键被分配给一个值时,后一个值将替换前一个值。你知道吗

def createDictionary(filename):
    f = open(filename, 'r')
    dic = {}
    for line in f:
        #line = line.strip()
        data = line.split(',')
        print(data)
        dic[data[0]] = data[1]
    return dic 

if __name__ == "__main__":
    x = createDictionary("textToEnglish.csv") 
    print type(x)
    # <class 'dict'>

    print len(x)
    # 4255

for k, v in x.items():
    print(k, v)

尽量不要同时使用print字典,尤其是有这么多的值,这会增加内存开销。了解如何使用for循环遍历键和值。你知道吗

尽管所提供的其他解决方案没有任何问题,但是通过使用python优秀的库,您可以简化并大大提升您的解决方案。你知道吗

Pandas是一个用Python处理数据的库,许多数据科学家都喜欢它。你知道吗

Pandas有一个简化的CSV接口来读取和解析文件,可以用来返回字典列表,每个字典包含一行文件。键将是列名,值将是每个单元格中的值。你知道吗

就你而言:

    import pandas

    def createDictionary(filename):
        my_data = pandas.DataFrame.from_csv(filename, sep=',', index_col=False)
        list_of_dicts = [item for item in my_data.T.to_dict().values()]
        return list_of_dicts

    if __name__ == "__main__":
        x = createDictionary("textToEnglish.csv") 
        print type(x)
        # <class 'list'>
        print len(x)
        # 4255
        print type(x[0])
        # <class 'dict'>

相关问题 更多 >