【问题标题】:Extracting Data from Multiple TXT Files and Creating a Summary CSV File in Python从多个 TXT 文件中提取数据并在 Python 中创建摘要 CSV 文件
【发布时间】:2014-09-17 01:56:26
【问题描述】:

我有一个包含大约 50 个 .txt 文件的文件夹,其中包含以下格式的数据。

=== Predictions on test data ===

 inst#     actual  predicted error distribution (OFTd1_OF_Latency)
     1        1:S        2:R   +   0.125,*0.875 (73.84)

我需要编写一个程序,结合以下内容:我的索引号 (i)、真实类的字母(R 或 S)、预测类的字母、以及每个分布预测(小数点后大于 1.0)。

我希望它在完成后如下所示,但最好是 .csv 文件。

ID   True   Pred   S      R
1    S      R      0.125  0.875
2    R      R      0.105  0.895
3    S      S      0.945  0.055
.    .      .      .      .
.    .      .      .      .
.    .      .      .      .
n    S      S      0.900  0.100

我是一个初学者,对于如何将所有这些解析然后连接和附加有点模糊。这就是我的想法,但如果这样更容易,请随意提出另一个方向。

for i in range(1, n):
   s = str(i)
   readin = open('mydata/output/output'+s+'out','r')
   #The files are all named the same but with different numbers associated
   output = open("mydata/summary.csv", "a")
   storage = []
   for line in readin:
     #data extraction/concatenation here
     if line.startswith('1'):
        id = i
        true = # split at the ':' and take the letter after it
        pred = # split at the second ':' and take the letter after it
         #some have error '+'s and some don't so I'm not exactly sure what to do to get the distributions
        ds = # split at the ',' and take the string of 5 digits before it
        if pred == 'R':
           dr = #skip the character after the comma but take the have characters after
        else: 
           #take the five characters after the comma
        lineholder = id+' , '+true+' , '+pred+' , '+ds+' , '+dr
     else: continue
   output.write(lineholder)

我认为使用索引将是另一种选择,但如果任何文件中的间距关闭并且我还没有确定这一点,它可能会使事情复杂化。

感谢您的帮助!

【问题讨论】:

    标签: python python-2.7 csv export-to-csv


    【解决方案1】:

    首先,如果你想使用 CSV,你应该使用 python 自带的 CSV 模块。更多关于这个模块的信息在这里:https://docs.python.org/2.7/library/csv.html 我不会演示如何使用它,因为它非常简单。

    至于读取输入数据,我的建议是如何分解数据本身的每一行。我假设输入文件中的数据行的值由空格分隔,并且每个值不能包含空格:

    def process_line(id_, line):
        pieces = line.split() # Now we have an array of values
        true = pieces[1].split(':')[1] # split at the ':' and take the letter after it
        pred = pieces[2].split(':')[1] # split at the second ':' and take the letter after it
        if len(pieces) == 6: # There was an error, the + is there
            p4 = pieces[4]
        else: # There was no '+' only spaces
            p4 = pieces[3]
        ds = p4.split(',')[0] # split at the ',' and take the string of 5 digits before it
        if pred == 'R':
            dr = p4.split(',')[0][1:] #skip the character after the comma but take the have??? characters after
        else:
            dr = p4.split(',')[0]
        return id_+' , '+true+' , '+pred+' , '+ds+' , '+dr
    

    我这里主要使用的是字符串的拆分函数:https://docs.python.org/2/library/stdtypes.html#str.split,还有一个地方是 str[1:] 的简单语法,可以跳过字符串的第一个字符(字符串毕竟是数组,我们可以使用这种切片语法)。

    请记住,我的函数不会处理任何错误或格式与您发布的示例不同的行。如果每一行中的值由制表符而不是空格分隔,则应将此行替换:pieces = line.split()pieces = line.split('\t')

    【讨论】:

    • 经过一些修改后效果非常好(将 ds 放在 if/else 下,因为如果 pred = S,那么它有星号)。谢谢!
    【解决方案2】:

    我认为你可以分离浮点数,然后在 re 模块的帮助下将其与字符串组合,如下所示:

    import re
    file = open('sample.txt','r')
    strings=[[num for num in re.findall(r'\d+\.+\d+',i) for i in file.readlines()]]
    print (strings)
    file.close()
    file = open('sample.txt','r')
    num=[[num for num in re.findall(r'\w+\:+\w+',i) for i in file.readlines()]]
    print (num)
    s= num+strings
    print s #[['1:S','2:R'],['0.125','0.875','73.84']] output of the code
    

    这个程序是为一行编写的,你也可以将它用于多行,但你需要为此使用循环

    sample.txt 的内容: 1 1:S 2:R + 0.125,*0.875 (73.84)

    2 1:S 2:R + 0.15,*0.85 (69.4)

    当您运行 prog 时,结果将是: [['1:S,'2:R'],['1:S','2:R'],['0.125','0.875','73.84'],['0.15,'0.85,' 69.4']]

    简单地连接它们

    【讨论】:

      【解决方案3】:

      这使用正则表达式和 CSV 模块。

      import re
      import csv
      
      matcher = re.compile(r'[[:blank:]]*1.*:(.).*:(.).* ([^ ]*),[^0-9]?(.*) ')
      filenametemplate = 'mydata/output/output%iout'
      
      output = csv.writer(open('mydata/summary.csv', 'w'))
      
      for i in range(1, n):
          for line in open(filenametemplate % i):
              m = matcher.match(line)
              if m:
                 output.write([i] + list(m.groups()))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-06
        • 1970-01-01
        • 2022-09-23
        • 2017-03-26
        • 1970-01-01
        • 2022-06-11
        • 2014-12-25
        相关资源
        最近更新 更多