【问题标题】:From txt file to Python dictionary从 txt 文件到 Python 字典
【发布时间】:2014-04-22 15:36:22
【问题描述】:

如何从以下格式的文本文件中获取数据:

abc 5
defg 8
ghi 58
jklmn 450
opqrstuv 8456

并将其添加到字典中。例如:第一个是 dictionary['abc']=5,最后一个是 dictionary['opqrstuv']=8456 等等。我需要添加所有数据(文本文件中的每一行)

【问题讨论】:

  • 通过编写 Python 程序?说真的,SO 不是一个“为我工作”的网站。这是一个问答网站。像您这样的读者会提出具体的问题,而其他读者会尝试回答这些问题。你有具体的编程问题吗?请参阅:stackoverflow.com/help/how-to-ask 以获得更多帮助。
  • 你的输入文件是否真的包含dictionary = {}这一行?
  • 不..我不应该把它放在那里。

标签: python file text dictionary compiler-construction


【解决方案1】:
dictionary = {}
with open('path/to/file') as infile:
    for line in infile:
        key,value = line.split(" ")
        dictionary[key] = int(value)

换句话说,逐行读取文件,并设置dict,使得每个键都是单个空格之前的区域,每个值是单个空格之后的区域,转换为int。

如果您始终拥有LETTERS NUMBERS,那么您可以使用正则表达式来做到这一点,但这似乎是不必要的困难。

与字典映射一样,试着考虑一下如果键发生冲突,你会想要什么作为标准行为,例如如果我阅读了"abc 5",但文件前面已经有"abc 10",那么dictionary["abc"] 存在。

(如果你喜欢,这里是丑陋的正则表达式解决方案:

import re
from operator import itemgetter as iget
with open('path/to/file') as infile:
    data = infile.read() # UGH
re_data = re.findall(r"([^\d\s]+)|([\d]+)", data)
dictionary = dict(zip( map(iget(0),re_data[0::2]),map(int,map(iget(1),re_data[1::2])) ))
# DOUBLE UGH. As a rule of thumb, if you're using three map
# functions in one line, REFACTOR.

【讨论】:

  • 我添加了一个int 转换(并删除了现在不需要的strip()
  • @TimPietzcker 感谢int 演员。 int("234 \t\n\n") == int("234")????我不知道。
  • 是的,前导/尾随空格被忽略。不错的功能,不是吗?
【解决方案2】:
dictionary={}
with open('file.txt','r') as f:
    for line in f.readlines():
        a,b = line.split()
        dictionary[a] = int(b)

【讨论】:

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