【问题标题】:python3 read text file into seperate dictionariespython3将文本文件读入单独的字典
【发布时间】:2017-04-13 13:29:23
【问题描述】:

我正在尝试弄清楚如何将以下示例文本文件读取到每个块的字典中,使用日期作为键,其余的作为值,但我无法解决:

Friday
10:00 - 10:30    Debrief
10:30 - 13:00    Track running
13:00 - 14:00    Lunch
14:00 - 18:00    Track running
18:00            End

Saturday
10:00 - 10:30    Debrief
10:30 - 13:00    Track running
13:00 - 14:00    Lunch
14:00 - 18:00    Track running
18:00            End

Sunday
10:00 - 10:30    Debrief
10:30 - 13:00    Track running
13:00 - 14:00    Lunch
14:00 - 18:00    Track running
18:00            End

这应该产生 3 个带有周五、周六和周日键的字典,每个块的其余部分应该是键的值。

这是我已经开始做的事情,但是我一直坚持如何将文本文件中的文本用作字典键,而且这看起来很麻烦,有没有简单的方法可以做到这一点,或者我是对的还是行?:

def schedule():
    flag = False
    with open("example.txt", 'r') as f:
        for line in f:
            if len(line.strip()) == 0:
                flag = True
            elif flag:
                # somehow use the day of the week to 
                # become the dictionary key
                flag = False
            else:
                # somehow use the rest of the block of text as the value

对不起,我没有任何工作代码

【问题讨论】:

    标签: python-3.x dictionary


    【解决方案1】:

    好吧,这是我快速抛出的一个示例,显然代码可以改进,它创建了一个带有星期几键的字典,并且每天都有一个计划中的每个任务的列表。

    def schedule():
    flag = False
    schedule = dict()
    days_of_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", 
                    "Saturday", "Sunday"]
    
    with open("example.txt", 'r') as f:
        for line in f:
            line_items = line.split()
            if line_items and line_items[0] in days_of_week:
                schedule[line_items[0]] = list()
                current_day = line_items[0]
            else:
                if line_items and current_day:
                    schedule[current_day].append(line_items)
    
    return schedule
    

    这将导致:

    {'Sunday': [['10:00', '-', '10:30', 'Debrief'], ['10:30', '-', '13:00', 'Track', 'running'], ['13:00', '-', '14:00', 'Lunch'], ['14:00', '-', '18:00', 'Track', 'running'], ['18:00', 'End']], 'Friday': [['10:00', '-', '10:30', 'Debrief'], ['10:30', '-', '13:00', 'Track', 'running'], ['13:00', '-', '14:00', 'Lunch'], ['14:00', '-', '18:00', 'Track', 'running'], ['18:00', 'End']], 'Saturday': [['10:00', '-', '10:30', 'Debrief'], ['10:30', '-', '13:00', 'Track', 'running'], ['13:00', '-', '14:00', 'Lunch'], ['14:00', '-', '18:00', 'Track', 'running'], ['18:00', 'End']]}
    

    【讨论】:

      【解决方案2】:

      在使用包含星期几的字典方面,我采用了与 Ilhicas 类似的方法。我更进一步,能够为每个字典条目的“值”提供一串所需的信息。

      with open('example.txt', 'r') as f:
          dictDays = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
          lines = f.read().splitlines()  #read lines but removes '\n'
          schDict = {}
          for text in lines:
              if text in dictDays:
                  schDict.update({text: ''})
                  del lines[lines.index(text)]
          connect = ['']
          count = 0
          for text in lines:
              if text != '':
                  connect[count] += (text + '\n')
              if text == '':
                  connect.append('')
                  count += 1
          for txtNum in range(len(connect)):
              dayKey = list(schDict.keys())[txtNum]
              schDict.update({dayKey:connect[txtNum]})
      
      print(schDict)
      

      我也是 Python 新手。我已经使用它大约 2 个月了,所以我确信这段代码可以稍微清理一下,但它应该包含解决问题所需的工具。

      【讨论】:

      • 很遗憾,如果列表超出范围,我无法正常工作
      • 嗯?这太有趣了。我只是将上面的代码复制并粘贴到 Atom 中的一个新的 .py 文件中,确保 open 函数指向正确的文件位置并正常运行。这是我得到的输出:{'Friday': '10:00 - 10:30 Debrief\n10:30 - 13:00 Track running\n13:00 - 14:00 Lunch\n14:00 - 18:00 Track running\n18:00 End\n', 'Saturday': '10:00 - 10:30 Debrief\n10:30 - 13:00 Track running\n13:00 - 14:00 Lunch\n14:00 - 18:00 Track running\n18:00 由于字符限制,我缩短了输出,但你明白了。
      • 'list out of range' 发生在您尝试通过空列表运行 for 循环时。您是从上面复制和粘贴代码还是稍微修改一下?如果我能看到代码,我可以帮助解决问题。
      • @iFunction 你能让代码工作吗?我的帖子有帮助吗?
      猜你喜欢
      • 1970-01-01
      • 2013-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      相关资源
      最近更新 更多