【问题标题】:Python - converting textfile contents into dictionary values/keys easilyPython - 轻松将文本文件内容转换为字典值/键
【发布时间】:2011-08-22 00:31:05
【问题描述】:

假设我有一个包含以下内容的文本文件:

line = "this is line 1"
line2 = "this is the second line"
line3 = "here is another line"
line4 = "yet another line!"

我想快速将这些转换为字典键/值,其中“line*”作为键,引号中的文本作为值,同时删除等号。

在 Python 中执行此操作的最佳方法是什么?

【问题讨论】:

  • 为什么要将它作为字典,而不是使用已经能理解这一点的众多配置文件解析器之一?
  • 那些是哪些?

标签: python dictionary formatting key


【解决方案1】:

inspectorG4dget 的urlopen 版本的答案可能如下所示:

from urllib.request import urlopen
url = 'https://raw.githubusercontent.com/sedeh/github.io/master/resources/states.txt'
response = urlopen(url)
lines = response.readlines()
state_names_dict = {}
for line in lines:
    state_code, state_name = line.decode().split(":")
    state_names_dict[state_code.strip()] = state_name.strip()

【讨论】:

    【解决方案2】:

    一行:

    d = dict((line.strip().split(' = ') for line in file(filename)))
    

    【讨论】:

    • Traceback(最近一次调用最后):文件“”,第 1 行,在 d = dict((line.strip().split(' = ') for line in file('F:\lines.txt'))) TypeError: 'dict' object is not callable
    • @jim,哪个版本的 Python?
    • 对于 Python 3,我认为你需要使用:d = {line.strip().split(' = ') for line in file(filename)},但我没有 Python 3,所以我无法测试它。
    【解决方案3】:
    f = open(filepath, 'r')
    answer = {}
    for line in f:
        k, v = line.strip().split('=')
        answer[k.strip()] = v.strip()
    
    f.close()
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2020-12-16
      • 2023-03-15
      • 2015-02-08
      • 2023-03-20
      • 2020-09-24
      • 1970-01-01
      • 2018-02-14
      • 2017-11-08
      相关资源
      最近更新 更多