【问题标题】:parsing a text file into lists with python使用python将文本文件解析为列表
【发布时间】:2019-12-02 19:33:34
【问题描述】:

所以我有一个生成的文本文件,我想将其解析为几个日期列表。我已经弄清楚每个“组”何时有一个日期,但我意识到我可能必须处理每个组的多个日期值。 我的 .txt 文件如下所示:

DateGroup1
20191129
20191127
20191126
DateGroup2
20191129
20191127
20191126
DateGroup3
2019-12-02
DateGroup4
2019-11-27
DateGroup5
2019-11-27

理想情况下,我可以将其解析为 5 个列表,其中包括每个组的日期。我好难过

【问题讨论】:

  • 请显示您的代码尝试并清楚地显示您需要的所需输出。不幸的是,“我很难过”不是我们可以解决的问题。见How to Ask

标签: python parsing


【解决方案1】:

只需遍历每一行,检查用于分组数据、删除换行符并存储每个新日期的密钥。

DATE_GROUP_SEPARATOR = 'DateGroup'
sorted_data = {}

with open('test.txt') as file:
    last_group = None
    for line in file.readlines():
        line = line.replace('\n', '')
        if DATE_GROUP_SEPARATOR in line:
            sorted_data[line] = []
            last_group = line
        else:
            sorted_data[last_group].append(line)

for date_group, dates in sorted_data.items():
    print(f"{date_group}: {dates}")

【讨论】:

    【解决方案2】:

    这是一个您可以构建的示例,每次它读取一个字符串而不是一个数字时,它都会创建一个新列表并将所有日期放在该组下

    import os
    
    #read file
    lineList = 0
    with open("test.txt") as f:
      lineList = f.readlines()
    
    #make new list to hold variables
    lists = []
    
    #loop through and check for numbers and strings
    y=-1
    for x in range(len(lineList)):
        #check if it is a number or a string
        if(lineList[x][0] is not None and not lineList[x][0].isdigit()):
            #if it is a string make a new list and push back the name
            lists.append([lineList[x]])
            y+=1
        else:
            #if it is the number append it to the current list
            lists[y].append(lineList[x])
    
    #print the lists
    for x in lists:
        print(x)
    

    【讨论】:

      【解决方案3】:

      首先阅读整个文本文件。然后您可以计算“DateGroup”的出现次数,这似乎是您的日期组分离中的常数部分。然后,您可以通过遍历任意两个“DateGroup”标识符之间或一个“DateGroup”标识符和文件末尾之间的所有数据来解析文件。尝试理解以下代码并在此基础上构建您的应用程序:

      file = open("dates.txt")
      text = file.read()
      file.close()
      
      amountGroups = text.count("DateGroup")
      
      list = []
      
      index = 0
      i = 0
      for i in range(amountGroups):
          list.append([])
      
          index = text.find("DateGroup", index)
          index = text.find("\n", index) + 1
          indexEnd = text.find("DateGroup", index)
          if(indexEnd == -1):
              indexEnd = len(text)
          while(index < indexEnd):
              indexNewline = text.find("\n", index)
              list[i].append(text[index:indexNewline])
              index = indexNewline + 1
      
      print(list)
      

      【讨论】:

        【解决方案4】:

        这第一部分只是为了展示如何处理带有数据的字符串,就好像它来自文件一样。如果您不想生成 OP 的实际文件但想在编辑器中明显地导入数据,这会有所帮助。

        import sys
        from io import StringIO  # allows treating some lines in editor as if they were from a file)
        
        dat=StringIO("""DateGroup1
        20191129
        20191127
        20191126
        DateGroup2
        20191129
        20191127
        20191126
        DateGroup3
        2019-12-02
        DateGroup4
        2019-11-27
        DateGroup5
        2019-11-27""")
        
        lines=[ l.strip() for l in dat.readlines()]    
        print(lines) 
        

        输出:

           ['DateGroup1', '20191129', '20191127', '20191126', 'DateGroup2', '20191129', '20191127', '20191126', 'DateGroup3', '2019-12-02', 'DateGroup4', '2019-11-27', 'DateGroup5', '2019-11-27']
        

        现在一种可能的方式来生成您想要的列表列表,同时确保涵盖两种可能的日期格式:

        from datetime import datetime
        b=[]
        for i,line in enumerate(lines):
            try:             # try first dateformat
                do = datetime.strptime(line, '%Y%m%d')
                a.append(datetime.strftime(do,'%Y-%m-%d'))
            except:
                try:         # try second dateformat
                    do=datetime.strptime(line,'%Y-%m-%d')
                    a.append(datetime.strftime(do,'%Y-%m-%d'))
                except:       # if neither date, append old list to list of lists  & make a new list
                    if a!=None:
                        b.append(a)
                    a=[]
            if i==len(lines)-1:
                b.append(a)
        
        b
        

        输出:

         [['2019-11-27'],
         ['2019-11-29', '2019-11-27', '2019-11-26'],
         ['2019-11-29', '2019-11-27', '2019-11-26'],
         ['2019-12-02'],
         ['2019-11-27'],
         ['2019-11-27']]
        

        【讨论】:

          【解决方案5】:

          TTP 也可以帮助解析此文本,这里是示例模板以及如何运行它的代码:

          from ttp import ttp
          
          data_to_parse = """
          DateGroup1
          20191129
          20191127
          20191126
          DateGroup2
          20191129
          20191127
          20191126
          DateGroup3
          2019-12-02
          DateGroup4
          2019-11-27
          DateGroup5
          2019-11-27
          """
          
          ttp_template = """
          <group name="date_groups.date_group{{ id }}">
          DateGroup{{ id }}
          {{ dates | to_list | joinmatches() }}
          </group>
          """
          
          parser = ttp(data=data_to_parse, template=ttp_template)
          parser.parse()
          print(parser.result(format="json")[0])
          

          上面的代码会产生这个输出:

          [
              {
                  "date_groups": {
                      "date_group1": {
                          "dates": [
                              "20191129",
                              "20191127",
                              "20191126"
                          ]
                      },
                      "date_group2": {
                          "dates": [
                              "20191129",
                              "20191127",
                              "20191126"
                          ]
                      },
                      "date_group3": {
                          "dates": [
                              "2019-12-02"
                          ]
                      },
                      "date_group4": {
                          "dates": [
                              "2019-11-27"
                          ]
                      },
                      "date_group5": {
                          "dates": [
                              "2019-11-27"
                          ]
                      }
                  }
              }
          ]
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-02-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-02-09
            • 1970-01-01
            • 2023-03-13
            • 1970-01-01
            相关资源
            最近更新 更多