从txt文件到Python字典

use*_*506 -1 python compiler-construction text dictionary file

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

abc 5
defg 8
ghi 58
jklmn 450
opqrstuv 8456
Run Code Online (Sandbox Code Playgroud)

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

Ada*_*ith 5

dictionary = {}
with open('path/to/file') as infile:
    for line in infile:
        key,value = line.split(" ")
        dictionary[key] = int(value)
Run Code Online (Sandbox Code Playgroud)

换句话说,逐行读取文件,并设置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.
Run Code Online (Sandbox Code Playgroud)

  • 是的,忽略前导/尾随空格.不错的功能,不是吗? (2认同)