Python:将文本文件转换为字典

时间:2017-08-03 16:15:06

标签: python list dictionary file-handling

我想将文本文件转换为键值对。 我的文字文件

21:54:26     From Rohan luthra : yes
21:54:36     From Ankit : yup
21:54:36     From Ankit : yup
21:55:04     From Rajesh : shubh shubh bolo sir

我想要做的是转换为键值对,如

{'Rohan luthra' : 'yes',
'Ankit' : 'yup,}
像这样^ 我找不到任何合适的解决方案。 我做了什么

with open(x) as f:
    lines = f.readlines()
    with open(x, 'r') as f:
        for line in f:
            splitLine = line.split()
            temp_dict[(splitLine[0])] = " ".join(splitLine[2:])
            # Dirty hack to remove timestamp
            temp_array = temp_dict.values()
            chat_dict = dict(s.split(':') for s in temp_array)
            pp.pprint(temp_dict)

但是当这个方法在一行中遇到两个“:”时失败了。 它返回:

Traceback (most recent call last):
  File "filereader.py", line 37, in <module>
    most_talkative()
  File "filereader.py", line 32, in most_talkative
    chat_dict = dict(s.split(':') for s in temp_array)
ValueError: dictionary update sequence element #35 has length 3; 2 is required

2 个答案:

答案 0 :(得分:0)

with open(x) as f:
    lines = f.readlines()
    with open(x, 'r') as y:
        for line in y:
            splitLine = line.split()
            temp_dict[(splitLine[0])] = " ".join(splitLine[2:])
            # Dirty hack to remove timestamp
            temp_array = temp_dict.values()
            chat_dict = dict(s.split(':')[:2] for s in temp_array)

这似乎有效! @Alan Leuthard给出的解决方案

循环仅适用于20行,而实际文件为100+行+

返回len(行)给出实际的no。文件中的行,即119。

答案 1 :(得分:0)

以下内容从提供的文件格式的任意长度版本创建字典。请记住,每个键只能有1个值,因此重复的键将被后来的值覆盖。

Y = load('testFile.txt');  %Load file
p = randperm(length(Y));   %List of random numbers between 0 and Y size

Y(:,1) = Y(p,1);
Y(:,2) = Y(p,2);
Y(:,3) = Y(p,4);