【问题标题】:Read a file, drop text fields, keep numeric ones读取文件,删除文本字段,保留数字字段
【发布时间】:2017-03-17 17:03:36
【问题描述】:

我想编写一个小 Python 脚本来绘制一些 .dat 文件。为此,我需要先处理文件。 .dat 文件如下所示:

(Real64
 (numDims 1)
 (size 513)
 (data 
   [ 90.0282291905089 90.94377050431068 92.31708247501335 93.38521400778211 94.60593575951782 95.67406729228657 97.04737926298925 97.96292057679104 ...]
 )
)

我想删除文本部分和“正常”括号。我只需要 [.....] 之间的数据。

我尝试过这样的事情:

from Tkinter import Tk
from tkFileDialog import askopenfilename

# just a small GUI to get the file
Tk().withdraw()
filename = askopenfilename()

import numpy as np

with open(filename) as f:
    temp = f.readlines(5) #this is the line in the .dat file

    for i in range(len(temp)-1):
        if type(temp[i]) == str:
            del temp[i]

但是,这总是会导致“超出范围的索引”。非常感谢您的帮助。

【问题讨论】:

  • 你从哪里得到这个.dat 文件?你能不能让生成它的东西给你另一种格式(比如 JSON)?如果没有,您可以用逗号替换空格并将其解析为 JSON。
  • 你是什么意思“删除文本部分”?清楚。向我们展示您给定输入的预期输出。应该(size 513) -> (513),或513 还是完全删除?您可以使用正则表达式完成所有这些操作,但您没有为我们指定您想要完成的具体操作。
  • 你想用del 完成什么?你为什么要检查字符串是否是字符串?
  • 顺便说一句,“.DAT”文件不是一个定义明确的术语,除了暗示一些文本或二进制文件。您不妨说“读取文本文件”。它是有效的 JSON 吗?等
  • 这种看起来像 lisp 程序...你试过在 lisp 中运行它吗? (它可能不是有效的 lisp...我不知道我已经有一段时间没有使用 lisp 了)

标签: python regex file text-parsing fileparsing


【解决方案1】:

我只需要 [.....]

之间的数据
# treat the whole thing as a string
temp = '''(Real64
 (numDims 1)
 (size 513)
 (data
   [ 90.0282291905089 90.94377050431068 92.31708247501335 ]
 )
)'''

# split() at open bracket; take everything right
# then split() at close bracket; take everything left
# strip() trailing / leading white space
number_string = temp.split('[')[1].split(']')[0].strip()

# convert to list of floats, because I expect you'll need to
number_list = [float(i) for i in number_string.split(' ')]

print number_string
print number_list

>>> 90.0282291905089 90.94377050431068 92.31708247501335
>>> [90.0282291905089, 90.94377050431068, 92.31708247501335]

【讨论】:

    【解决方案2】:
    print re.findall("\[([0-9. ]+)\]",f.read())
    

    这被称为regular expression,它说找到我所有的东西,即两个方括号之间的数字句点和空格

     \[   # literal left bracket
     ( # capture the stuff in here
     [0-9. ] # accept 0-9 and . and space
    + # at least one ... probably more
     ) # end capture group
     \] # literal close bracket
    

    或者你可以使用类似pyparsing的东西

    inputdata = '''(Real64
     (numDims 1)
     (size 513)
     (data
       [ 90.0282291905089 90.94377050431068 92.31708247501335 93.38521400778211 94.60593575951782 95.67406729228657 97.04737926298925 97.96292057679104 ...]
     )
    )
    '''
    from pyparsing import OneOrMore, nestedExpr
    
    data = OneOrMore(nestedExpr()).parseString(inputdata)
    print "GOT:", data[0][-1][2:-1]
    

    【讨论】:

    • 感谢这确实帮助了我!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 2014-10-29
    相关资源
    最近更新 更多