【问题标题】:Extracting data from text file in Python在 Python 中从文本文件中提取数据
【发布时间】:2018-12-02 13:46:54
【问题描述】:

我有一个具有如下高级结构的文本文件:

CATEG:
DATA1
DATA2
...
DATA_N
CATEG:
DATA1
....

我希望打开这个文本文件,并解析 CATEG: 的每个实例,将其间的内容分开。但是,我对open 方法以及它在阅读时如何处理每一行中的新行感到非常烦恼。

即使用f = open('mydata.txt', 'r')f.readlines() 会导致很多不必要的换行符,并使得被上面的数据结构拆分很烦人。有人有任何提示吗?不幸的是,令人讨厌的是数据集。

【问题讨论】:

标签: python file parsing io


【解决方案1】:

试试 read().splitlines()。

例如:

from io import StringIO

def mkString():
    return StringIO("""CATEG:
        DATA1
        DATA2
        ...
        DATA_N
        CATEG:
        DATA1
        ....""")

mkString().read().splitlines()

【讨论】:

    【解决方案2】:

    试试下面的代码:

    with open('mydata.txt') as f:
      for line in f:
        line = line.strip(' \t\r\n')  # remove spaces and line endings
        if line.ednswith(';'):
          pass # this is category definition
        else:
          pass # this is data line
    

    【讨论】:

      【解决方案3】:

      试试这个:

      with open('text.txt') as file:
      text = file.read()
      text = text.replace('\n', ' ')
      s = text.split('CATEG:')
      s = [x.strip() for x in s if x != '']
      print(s)
      

      【讨论】:

        【解决方案4】:

        在你的序列周围写一个小包装器,去掉所有的换行符:

        def newline_stripper(seq):
            for s in seq:
                # or change this to just s.rstrip() to remove all trailing whitespace
                yield s.rstrip('\n')
        

        然后当你去迭代时用它包装你的文件对象:

        with open('text_file.txt') as f:
            for line in newline_stripper(f):
                # do something with your now newline-free lines
        

        这将保留您对文件的逐行读取,而不是像read().splitlines() 那样一次性读取所有文件。

        【讨论】:

          【解决方案5】:

          你可以使用itertools.groupby:

          from itertools import groupby
          
          with open(filename) a f:
              categs = [list(group) for (key, group) in groupby(f.splitlines(), key='CATEG:')]
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-03-13
            • 1970-01-01
            • 1970-01-01
            • 2020-12-20
            • 1970-01-01
            • 1970-01-01
            • 2018-03-08
            相关资源
            最近更新 更多