【问题标题】:python--import data from file and autopopulate a dictionarypython--从文件中导入数据并自动填充字典
【发布时间】:2013-12-22 22:16:49
【问题描述】:

我是 python 新手,正在尝试完成以下任务。 一个文本文件包含格式有点奇怪的数据,我想知道是否有一种简单的方法来解析它并使用正确的键和值自动填充一个空字典。

数据看起来像这样

01> A B 2          ##01> denotes the line number, that's all
02> EWMWEM         
03> C D 3
04> EWWMWWST
05> Q R 4
06> WESTMMMWW

因此,每一对行都描述了机械臂的一整套指令。第 1-2 行用于 arm1,3-4 用于 arm 2,依此类推。第一行说明位置,第二行说明一组指令(运动、方向变化、转弯等)

我正在寻找的是一种导入此文本文件、正确解析它并填充将生成自动键的字典的方法。请注意,该文件仅包含值。这就是为什么我很难过。如何告诉程序生成 armX(其中 X 是从 1 到 n 的 ID)并为其分配一个元组(或一对)以便字典读取。

dict = {'arm1': ('A''B'2, EWMWEM) ...}

如果新手式的词汇是多余的或不清楚的,我很抱歉。请告诉我,我很乐意澄清。

易于理解的注释代码将帮助我了解概念和动机。

只是为了提供一些上下文。程序的重点是加载所有指令,然后执行手臂上的方法。因此,如果您认为有一种更优雅的方式可以在不加载所有说明的情况下执行此操作,请提出建议。

【问题讨论】:

  • 'A''B'2EWMWEM 是字符串吗?
  • 我猜他想要'AB2'和'EWMWEM'。
  • @sPaz:感谢您的提问。 'A' 'B' 是否为 'AB' 无关紧要。但是,我需要将 2 设为 int。
  • 没有像'AB'2 这样的数据类型。你可以做{'arm1': ('AB',2,EWMWEM)...}

标签: python parsing file-io dictionary


【解决方案1】:

我会这样做:

mydict = {} # empty dict
buffer = ''
for line in open('myFile'): # open the file, read line by line
    linelist = line.strip().replace(' ', '').split('>') # line 1 would become ['01', 'AB2']
    if len(linelist) > 1: # eliminates empty lines
        number = int(linelist[0])
        if number % 2: # location line
            buffer = linelist[1] # we keep this till we know the instruction
        else:
            mydict['arm%i' % number/2] = (buffer, linelist[1]) # we know the instructions, we write all to the dict

【讨论】:

  • 看起来不错。虽然我认为行号01> 只是为了这个问题。不管怎样,这应该是一个好的开始。
  • 小心使用单词 dict 作为变量名。 isinstance(dict,dict) 报错
【解决方案2】:
def get_instructions_dict(instructions_file):
    even_lines = []
    odd_lines = []
    with open(instructions_file) as f:
        i = 1
        for line in f:
            # split the lines into id and command lines
            if i % 2==0:
                # command line
                even_lines.append(line.strip())
            else:
                # id line
                odd_lines.append(line.strip())
            i += 1

    # create tuples of (id, cmd) and zip them with armX ( armX, (id, command) )
    # and combine them into a dict
    result = dict( zip ( tuple("arm%s" % i for i in range(1,len(odd_lines)+1)),
                      tuple(zip(odd_lines,even_lines)) ) )

    return result

>>> print get_instructions_dict('instructions.txt')
{'arm3': ('Q R 4', 'WESTMMMWW'), 'arm1': ('A B 2', 'EWMWEM'), 'arm2': ('C D 3', 'EWWMWWST')}

注意dict 键未排序。如果这很重要,请使用OrderedDict

【讨论】:

  • 你能解释一下这部分吗? result = dict( zip ( tuple("arm%s" % i for i in range(1,len(odd_lines)+1)), tuple(zip(odd_lines,even_lines)) ) )
  • zip 接受两个列表/元组并使用每个列表/元组的第 n 个元素创建一个元组(即,zip([1,2,3],[4,5,6])==[(1,4),(2,5),(3,6)] dict 接受一个列表/元组并将其转换为带有第一个元素作为键,所以dict([(1,4),(2,5),(3,6)])=={1:4,2:5,3:6}...所以正如上面的评论所说,该行使用 (id, cmd) 的元组压缩 armX 并将其转换为字典
  • 然后尝试zip(('a','b','c'),tuple(zip((1,2,3),(4,5,6))))==[('a', (1, 4)), ('b', (2, 5)), ('c', (3, 6))]...最后是dict(zip(('a','b','c'),tuple(zip((1,2,3),(4,5,6)))))=={'a': (1, 4), 'b': (2, 5), 'c': (3, 6)}
【解决方案3】:
robot_dict = {}
arm_number = 1
key = None
for line in open('sample.txt'):
   line = line.strip().replace("\n",'')
   if not key:
       location = line
       key = 'arm' + str(arm_number) #setting key for dict
   else:
       instruction = line
       robot_dict[key] = (location,line)
       key = None #reset key
       arm_number = arm_number + 1

【讨论】:

  • 如果这是一个大文件,你不想在内存中加载整个东西,也要小心使用index + 1
  • 您能否详细说明此评论。大有多大?另外,有没有办法避免呢?我很想知道任何优雅的解决方案。程序的重点是加载所有指令,然后执行手臂上的方法。
  • nm,实际上我认为这是一个有争议的问题,因为我们正在创建一个包含所有内容的字典。
猜你喜欢
  • 2015-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-28
  • 2013-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多