Python,负数字符串转浮点数

3

这是一个非常简单的问题,但我却把它搞得复杂了,并且不断地遇到障碍。

我正在尝试解析一个包含点云信息(x,y,z)的简单文本文件。

它看起来像这样:

vertices:
v -543.243 -494.262 1282
v -538.79 -494.262 1282
v -536.422 -496.19 1287
v -531.951 -496.19 1287
v -527.481 -496.19 1287
v -213.909 -223.999 581
v -212.255 -224.384 582
v -209.15 -223.228 579
v -207.855 -223.999 581
v -205.482 -223.613 580
v -203.468 -223.613 580
v -201.106 -223.228 579
v -199.439 -223.613 580
v -197.765 -223.999 581
v -195.41 -223.613 580
v -193.062 -223.228 579
v -190.721 -222.842 578
v -189.04 -223.228 579
v -187.998 -224.384 582
v -185.976 -224.384 582
v -183.955 -224.384 582
v -181.621 -223.999 581
v -179.293 -223.613 580
v -177.279 -223.613 580
v -175.264 -223.613 580
v -173.549 -223.999 581
v -171.531 -223.999 581
v -169.513 -223.999 581
v -167.495 -223.999 581
v -165.761 -224.384 582
v -163.74 -224.384 582
v -161.718 -224.384 582
v -159.697 -224.384 582
v -157.946 -224.77 583
v -155.921 -224.77 583
v -153.896 -224.77 583
v -151.871 -224.77 583
v -149.847 -224.77 583
v -147.568 -224.384 582

好的,没问题。

接下来我在Blender中使用Python将这些点转换为顶点:

它看起来像这样:`

    #Open the file
try:
    f=open(path, 'r')
except:
    print ("Path is not Valid")


#Create an array of 
verts = []
#verts=[float(e) for e in verts if e]
#values = []

for line in f:
    lines = f.readline() 
    #values = ([c for c in lines if c in '-1234567890.'])
    if line.startswith("v "): #Go through file line by line
        read = lines.strip(' v\n').split(',') #remove the v,split@, 
            #read = values.split(',')
        #loop over all stuff in read, remove non-numerics
        for d in read:
            d= d.strip('-').split(' ')
            print("d:", (d))
            for n in d:
                n = n.strip('-')
                verts = verts.append(float(n[0]))
                #verts = verts.append(float(n[2]))
                #verts = verts.append(float(n[3]))
                print("vertsloops", d[0])
            print("read1", read[0])
            print(read)
            print("oo1verts", verts)
             ##################
             #Extend the array# 
             #print ("Could not use the line reading: %s"%read)


# Create a new mesh, it is now empty
mesh = bpy.data.meshes.new("Cube")
# Create empty vertices field in the mesh
mesh.vertices.add(len(verts))
# Add vertices
mesh.vertices.foreach_set("co", verts)


#Add a new empty object named "Read the PointCloud Data"
obj = bpy.data.objects.new("Read the PointCloud Data", mesh)
# Link object to current scene
bpy.context.scene.objects.link(obj)
`

一些方式,我已经尝试了许多不同的字符串分割组合,但仍然出现错误。我知道这是一项简单的任务!?请给予建议!
我得到的错误看起来像:
d: ['-536.422', '-496.19', '1287']
Traceback (most recent call last):
  File "/Users/.../importpoints.blend/importpoints", line 37, in <module>
ValueError: could not convert string to float: '-'
Error: Python script fail, look in the console for now...

然后像这样:

d: ['536.422', '-496.19', '1287']
vertsloops 536.422
Traceback (most recent call last):
  File "/Users/.../importpoints.blend/importpoints", line 37, in <module>
AttributeError: 'NoneType' object has no attribute 'append'
Error: Python script fail, look in the console for now...

有一个问题是,为什么float('-531')不会被处理为负数。目前,它遇到“-”字符串并认为它不是数字,因此无法转换它。但它是负数,我该如何表示?

谢谢。


要明确的是,起初我没有使用n.strip('-'),我尝试使用它来省略第一个错误。但我想包括负浮点数... - umbrellaSriracha
破折号是不是除了普通的ASCII减号之外的其他字符? - tripleee
5个回答

3

将负数字符串转换为浮点数没有问题。

>>> float('-5.6')
-5.6
>>> float('-531')
-531.0

这里有一个解析单行的例子。
>>> line = 'v -543.243 -494.262 1282'
>>> line.split()
['v', '-543.243', '-494.262', '1282']
>>> v, x, y, z = line.split()
>>> x 
'-543.243'
>>> y
'-494.262'
>>> z
'1282'

现在我们进行转换:
>>> x = float(x)
>>> x
-543.243

2

让你的阅读更简短:

verts = []
for line in f:
    if line.startswith('v '):
        verts.append([float(val) for val in line.split()[1:]])

这应该替换您完整的for line in f:循环。请确保文件中没有其他以v开头的行。也许值后面有一个空行,所以可以在那里停止读取。
现在verts看起来像这样:
[[-543.243, -494.262, 1282.0],
 [-538.79, -494.262, 1282.0],
 [-536.422, -496.19, 1287.0],
 [-531.951, -496.19, 1287.0],
 [-527.481, -496.19, 1287.0],
 [-213.909, -223.999, 581.0],
 [-212.255, -224.384, 582.0],
 [-209.15, -223.228, 579.0],
 [-207.855, -223.999, 581.0],
 [-205.482, -223.613, 580.0],
 [-203.468, -223.613, 580.0],
 [-201.106, -223.228, 579.0],
 [-199.439, -223.613, 580.0],
 [-197.765, -223.999, 581.0],
 [-195.41, -223.613, 580.0],
 [-193.062, -223.228, 579.0],
 [-190.721, -222.842, 578.0],
 [-189.04, -223.228, 579.0],
 [-187.998, -224.384, 582.0],
 [-185.976, -224.384, 582.0],
 [-183.955, -224.384, 582.0],
 [-181.621, -223.999, 581.0],
 [-179.293, -223.613, 580.0],
 [-177.279, -223.613, 580.0],
 [-175.264, -223.613, 580.0],
 [-173.549, -223.999, 581.0],
 [-171.531, -223.999, 581.0],
 [-169.513, -223.999, 581.0],
 [-167.495, -223.999, 581.0],
 [-165.761, -224.384, 582.0],
 [-163.74, -224.384, 582.0],
 [-161.718, -224.384, 582.0],
 [-159.697, -224.384, 582.0],
 [-157.946, -224.77, 583.0],
 [-155.921, -224.77, 583.0],
 [-153.896, -224.77, 583.0],
 [-151.871, -224.77, 583.0],
 [-149.847, -224.77, 583.0],
 [-147.568, -224.384, 582.0]]

0

谢谢大家,这帮了我很多。以下是最终代码,如果有人需要的话。

#path='Insert Path here' 

path='/OBJS2015-12-04-20-26-38-532.txt'

print('hello world')
######################################################################################

#Open the file
try:
    f=open(path, 'r')
except:
    print ("Path is not Valid")


#Create an array of vertices

vertices = []
#vee = []
t = ()
for line in f:
    if line.startswith('v '):
        vee = [float(val) for val in line.split()[1:]]
        t = tuple(vee)
        vertices.append(t)


#Define vertices, faces, edges
verts = vertices
faces = []


#Define mesh and object
mesh = bpy.data.meshes.new("Cube")
object = bpy.data.objects.new("Cube", mesh)

#Set location and scene of object
object.location = bpy.context.scene.cursor_location
bpy.context.scene.objects.link(object)

#Create mesh
mesh.from_pydata(verts,[],faces)
mesh.update(calc_edges=True)

0

所以只是为了补充答案...

首先,您应该在 Except 从句中退出程序,因为程序将继续运行并引发值错误,导致 f 未定义。

except:
    print "Invalid Path"
    exit() #Or some other way to exit

其次,假设您以读取模式正确打开了文件,那么您不应该执行lines.split('\ n')以获取每个不同的行吗?
lines = lines.split('\n') ##Creates a list of new-lines

再次补充一下答案...希望这能有所帮助!


0

对于其他人来说,如果遇到这个问题,可能是因为使用了非ASCII字符来表示“-”。只需使用正则表达式或其他方法修复浮点表示中的非ASCII字符,转换就可以正常工作。更多详细信息请参见Python将字符串转换为浮点数时出现负数错误


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接