Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中读取一些混乱的文件_Python_Io - Fatal编程技术网

在Python中读取一些混乱的文件

在Python中读取一些混乱的文件,python,io,Python,Io,我为类型为的文件编写了一个小的解析函数。在这种文件格式中,第一行应该是字母“OFF”,第二行应该是3个数字,指示文件其余部分的大小 我有数千个这样的文件。但是,在这些文件中,有一小部分是随机的,前两行连接不正确(不知道为什么)。除了使用readline()而不是readlines()进行迭代之外,我似乎无法在阅读时找到解决此问题的方法 还请假设更改所有文件也是不切实际的(我考虑过尝试一个bash脚本,但它是一个公共数据集,以后可能会继续使用) 有没有关于如何处理这些损坏的标题行的建议 以下是我当

我为类型为的文件编写了一个小的解析函数。在这种文件格式中,第一行应该是字母“OFF”,第二行应该是3个数字,指示文件其余部分的大小

我有数千个这样的文件。但是,在这些文件中,有一小部分是随机的,前两行连接不正确(不知道为什么)。除了使用
readline()
而不是
readlines()
进行迭代之外,我似乎无法在阅读时找到解决此问题的方法

还请假设更改所有文件也是不切实际的(我考虑过尝试一个bash脚本,但它是一个公共数据集,以后可能会继续使用)

有没有关于如何处理这些损坏的标题行的建议

以下是我当前的解析函数:

import numpy as np
def off_vertex_parser(self, path_to_off_file):
    print path_to_off_file
    # Read the OFF file
    with open(path_to_off_file, 'r') as f:
        contents = f.readlines()

    # Find the number of vertices contained
    num_vertices = int(contents[1].strip().split(' ')[0])

    # Convert all the vertex lines to a list of lists
    vertex_list = [map(float, contents[i].strip().split(' ')) 
                    for i in range(2, 2+num_vertices)]

    # Return the vertices as a 3 x N numpy array
    return np.array(vertex_list).transpose(1,0)
下面是.off文件的两个示例。第一种格式正确:

OFF
5 0 0
-12.280500 26.701300 10.653150
-12.575700 26.313400 11.003550
-12.569100 26.309300 10.653150
-13.208100 25.441200 10.653150
-12.569100 26.309300 10.653150
OFF5 0 0
-12.280500 26.701300 10.653150
-12.575700 26.313400 11.003550
-12.569100 26.309300 10.653150
-13.208100 25.441200 10.653150
-12.569100 26.309300 10.653150
第二种格式不正确:

OFF
5 0 0
-12.280500 26.701300 10.653150
-12.575700 26.313400 11.003550
-12.569100 26.309300 10.653150
-13.208100 25.441200 10.653150
-12.569100 26.309300 10.653150
OFF5 0 0
-12.280500 26.701300 10.653150
-12.575700 26.313400 11.003550
-12.569100 26.309300 10.653150
-13.208100 25.441200 10.653150
-12.569100 26.309300 10.653150

您可以从以下任一格式解析顶点:

# Find the number of vertices contained
if contents[0].strip().lower() != 'off':
    num_vertices = int(contents[0].strip()[3:].split(' ')[0])
    start_line = 1
else:
    num_vertices = int(contents[1].strip().split(' ')[0])
    start_line = 2

# Convert all the vertex lines to a list of lists
vertex_list = [map(float, contents[i].strip().split(' ')) 
                for i in range(start_line, start_line+num_vertices)]

简单但有效。谢谢透过树林我看不见森林。。。