【问题标题】:Creating a dictionary in python from txt file从txt文件在python中创建字典
【发布时间】:2021-05-10 03:47:15
【问题描述】:

我知道以前有人问过这个问题的变体,但我仍然在努力将 txt 文件移动到字典中。 txt 文件的名称和数量用 ":" 分隔。我遇到了 strip 函数没有删除空行的问题。我遇到的另一个问题是,如果两行具有相同的键,我想对这些值求和。我对 python 还是比较陌生,所以任何帮助都将不胜感激!

enter image description here

【问题讨论】:

  • 欢迎来到 SO,您应该粘贴代码而不是图像,添加一个您尝试过的示例以及问题所在。
  • 那个文件对我来说看起来很糟糕。那是怎么回事?
  • strip 函数不会删除空行。它删除字符串开头和结尾的空格。如果该行是空白的,您将得到一个空字符串,您需要自己跳过。
  • 例如line = line.strip() 后跟 if line == '': continue

标签: python dictionary txt


【解决方案1】:

非常简单但不安全,有很多地方你的程序可能会崩溃,但你可能并不关心

def loadToDict(path):
    f = open(path)
    d = {} 
    for line in f:
        line = line.strip()
        if line == "": # ignore empty line
            continue
        key, value = line.split(":") # decompose
        if key in d: # contains so add
            d[key] += int(value)
        else:
            d[key] = int(value)
    return d

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多