gpt4 book ai didi

python - 用Python读取一些乱七八糟的文件

转载 作者:行者123 更新时间:2023-12-01 02:12:13 25 4
gpt4 key购买 nike

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

我有数千个这样的文件。然而,在这些文件的一小部分随机百分比中,前两行被错误地连接(不知道为什么)。由于缺少使用 readline() 而不是 readlines() 进行迭代,我似乎无法在阅读时找到解决此问题的方法。

还请假设更改所有文件也是不切实际的(我考虑过尝试 bash 脚本,但它是一个公共(public)数据集,那么我将来可能会继续从中提取)。

有什么建议可以解决这些损坏的标题行吗?

这是我当前的解析函数:

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

最佳答案

您可以解析任一格式的顶点,例如:

# 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)]

关于python - 用Python读取一些乱七八糟的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48634010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com