【问题标题】:How to read a file with rows spread on multiple lines?如何读取行分布在多行的文件?
【发布时间】:2019-02-14 13:58:25
【问题描述】:

我的文件中的行分布在多行上。在我文件的以下块中,第一行从 0.0000000000000000E+00 开始,而第二行从 1.5625000000000000E-02 开始。如何将 0.0000000000000000E+00 到 1.5625000000000000E-02 之前的一作为一行读取?

我正在尝试 numpy 的 genfromtxt() 函数和 pandas 的 read_csv(),但我还不能与系统交流我打算做什么。

#I have put quotation marks here just to indicate the start and end of rows. They
#are not part of the file.

"0.0000000000000000E+00 

00000000     4.9999998882412910E-03       8.7714487508765548E-03  

00000001     5.0000002374872565E-04       5.0877144875087654E-01"


"1.5625000000000000E-02 

00000000     4.9999998882412910E-03       8.4622513106357884E-03 

00000001     5.0000002374872565E-04       5.0864039953085094E-01"

正确读取后,我的输入数组如下所示:

0.0000000000000000E+00   00000000    4.9999998882412910E-03       8.7714487508765548E-03      00000001   5.0000002374872565E-04       5.0877144875087654E-01

1.5625000000000000E-02   00000000    4.9999998882412910E-03       8.4622513106357884E-03      00000001   5.0000002374872565E-04       5.0864039953085094E-01

【问题讨论】:

  • 您是否尝试过使用thispandas。方法是使用pd.read_csv(filename, sep=" ")
  • 你能分享原始数据的文件吗?
  • 我们可以假设列数吗?
  • @Dillon,它给出“ParserError: Error tokenizing data. C error: Expected 34 fields in line 106, saw 36”
  • @Christophe,在这里显示的数据中,列数应该是7。如果你看到实际的file,列数是37。

标签: python pandas numpy file-read


【解决方案1】:

这应该适用于正则表达式包。

text = """

0.0000000000000000E+00 

00000000     4.9999998882412910E-03       8.7714487508765548E-03  

00000001     5.0000002374872565E-04       5.0877144875087654E-01


1.5625000000000000E-02 

00000000     4.9999998882412910E-03       8.4622513106357884E-03 

00000001     5.0000002374872565E-04       5.0864039953085094E-01"""

代码:

import re
xx = re.split(pattern="\n\n\n", string=text)

for xy in xx:
    xy = re.sub(pattern="\s+", repl=" ", string=xy)
    print(xy)
    print("*"*55)

输出:

0.0000000000000000E+00 00000000 4.9999998882412910E-03 8.7714487508765548E-03 00000001 5.0000002374872565E-04 5.0877144875087654E-01
*******************************************************
1.5625000000000000E-02 00000000 4.9999998882412910E-03 8.4622513106357884E-03 00000001 5.0000002374872565E-04 5.0864039953085094E-01
*******************************************************

【讨论】:

    【解决方案2】:

    假设您希望在输出数据中有7 行,这是您的file。所以这里是如何将其解析为pandas 数据框:

    import pandas as pd
    
    with open('temp.txt') as f:
        d = f.read().split()
    
    data = {'col1': [], 'col2': [], 'col3': [], 'col4': [], 'col5': [], 'col6': [], 'col7': []}
    for i in range(0, len(d), 7):
        for j in range(7):
            data['col{}'.format(j+1)].append(d[j])
    
    df = pd.DataFrame(data)
    

    输出:

    【讨论】:

      【解决方案3】:

      下面的代码应该能正确解析你的文件内容:

      import re
      import pandas
      
      sample = """0.0000000000000000E+00 
      
      00000000     4.9999998882412910E-03       8.7714487508765548E-03  
      
      00000001     5.0000002374872565E-04       5.0877144875087654E-01
      
      
      1.5625000000000000E-02 
      
      00000000     4.9999998882412910E-03       8.4622513106357884E-03 
      
      00000001     5.0000002374872565E-04       5.0864039953085094E-01
      """
      
      
      def load_matrix(content):
          lines = (line for line in content.splitlines() if len(line.strip()) > 0)
      
          rows = list()
          row = list()
          for line in lines:
              fields = line.split()
              is_continuation = re.match(r'^\d{8}$', fields[0])
              if is_continuation:
                  row += [float(value) for value in fields[1:]]
      
              else:
                  if (len(row) > 0):
                      rows.append(row)
      
                  row = [float(value) for value in fields]
      
          rows.append(row)
          return pandas.DataFrame(rows)
      
      print(load_matrix(sample))
      

      显示:

                0      1         2       3         4
      0  0.000000  0.005  0.008771  0.0005  0.508771
      1  0.015625  0.005  0.008462  0.0005  0.508640
      

      【讨论】:

        【解决方案4】:

        输出为两个列表:

        import re
        
        file_object = open("over.txt",'rU')
        
        df1=[]
        df2=[]
        content = ''
        
        try:
            for line in file_object:
                content = content + line
        finally:
             file_object.close()
        
        words = re.split(pattern="\n\n\n", string=content)
        
        num = re.sub(pattern="\s+", repl=",", string=words[0])
        for i in num.split(","):
            df1.append(float(i))
        
        num = re.sub(pattern="\s+", repl=",", string=words[1])
        for i in num.split(","):
            df2.append(float(i))
        
        print df1
        print df2
        

        输出:

        [0.0, 0.0, 0.004999999888241291, 0.008771448750876555, 1.0, 0.0005000000237487257, 0.5087714487508765]
        [0.015625, 0.0, 0.004999999888241291, 0.008462251310635788, 1.0, 0.0005000000237487257, 0.5086403995308509]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-24
          • 1970-01-01
          • 2021-02-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多