Python:文本文件到字典

2024-10-03 21:24:59 发布

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

我想把文本文件转换成键值对行方式。 我的文本文件

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

Tags: infrommostforlinearraytempdict
2条回答

下面将从提供的文件格式的任意长度版本创建字典。请记住,每个键只能有一个值,因此重复的键将被后面的值覆盖。你知道吗

x = 'path\\to\\file'
temp_dict = dict()
chat_dict = dict()
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.update(dict(s.split(':')[:2] for s in temp_array))
print(chat_dict)
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(行)给出文件中的实际行数,即119。你知道吗

相关问题 更多 >