【问题标题】:Python: Text file into dictionaryPython:文本文件到字典
【发布时间】:2018-01-11 09:02:17
【问题描述】:

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

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

【问题讨论】:

  • 您好,欢迎您!看起来您希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的程序员编写代码,但他们通常只会在发布者已经尝试自己解决问题时提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出以及您实际获得的输出(控制台输出、回溯等)。您提供的详细信息越多,您可能收到的答案就越多。检查FAQHow to Ask
  • 如果没有合适的解决方案,请做一个,展示你的努力,如果卡住了再问一个问题。
  • “失败”是什么意思?
  • 回溯(最近一次调用最后):文件“filereader.py”,第 37 行,在 most_talkative() 文件“filereader.py”,第 32 行,在 most_talkative chat_dict = dict(s .split(':') for s in temp_array) ValueError: dictionary update sequence element #35 has length 3; 2 是必需的
  • 不要使用推导式。将其分解为一个真正的循环,在调用 dict() 之前拆分,并且只使用 dict() 调用中每个拆分的前 2 个值。或者如果您需要第二个 ':' 之后的信息,请使用其他逻辑,我想您也可以将 s.split(':')[:2] 发送到理解中的 dict() 调用。

标签: python list dictionary file-handling


【解决方案1】:

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

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)

【讨论】:

  • 我有重复键!
【解决方案2】:
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(lines) 给出实际编号。文件中的行数,即 119。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    相关资源
    最近更新 更多