首页 文章

从3d坐标中删除撇号和非数字字符 - python

提问于
浏览
0

我试图在包含3D坐标的txt文件中读取x y和z数组 . 但是,在打印结果时,字符串包含撇号和其他我不想要的非数字字符'('' - 因为我将使用数据来绘制图表 . 我该如何删除这些?作为旁注,我还想采取第一行并将其作为新矩阵x1,y1,z1 . 我已经尝试将字符串转换为浮点数,从实际文本文件中删除括号,使用is.digit(由于存在非数字字符,返回false,包含源位置的())以及此处发布的其他方法徒劳无功 . python /编程新手 - 感谢您的帮助 .

码:

x=[]
y=[]
z=[]

data = np.genfromtxt('data0.txt', delimiter=',', dtype=float)
for row in myFile:
  x.append(row[0])
  y.append(row[1])
  z.append(row[2])

print(x)
print(y)
print(z)`

结果:

['(-0.3', '-1.1', '-1.7', '-0.74', '-0.14', '-0.23', '-12.0', '-1.8', 
'-1.17', '-17.0', '0.43', '-0.58', '-1.58', '9.8', '-0.76', '-0.98', 
'-1.1']
[' -1.1', '-2.45', '-4.4', '-1.77', '-0.34', '-0.57', '-28.0', '-4.5', 
'-2.63', '-47.0', '0.65', '-1.58', '-3.79', '23.35', '-1.5', '-2.49', 
'-2.8']
[' 1.36)', '2.7', '5.5', '2.4', '0.24', '0.54', '32.0', '6.9', '3.25', 
'58.0', '-1.0', '1.94', '4.6', '-28.29', '1.35', '3.7', '3.26']

期望的结果:x,y,z值打印在没有撇号且没有'()'括号的矩阵中 .

这是源文件(在我的jupyter中心上传):

-0.3, -1.1, 1.36
-1.1,-2.45,2.7
-1.7,-4.4,5.5
-0.74,-1.77,2.4
-0.14,-0.34,0.24
-0.23,-0.57,0.54
-12.0,-28.0,32.0
-1.8,-4.5,6.9
-1.17,-2.63,3.25
-17.0,-47.0,58.0
0.43,0.65,-1.0
-0.58,-1.58,1.94
-1.58,-3.79,4.6
9.8,23.35,-28.29
-0.76,-1.5,1.35
-0.98,-2.49,3.7
-1.1,-2.8,3.26

2 回答

  • 0

    您可以迭代每个列表,过滤掉大括号并将每个项目转换为浮点数,因此:

    float(a.replace('(','').replace(')',''))
    

    对于列表中的每个项目 a .

  • 0

    原始程序在我将其更改为时可以使用

    import numpy as np
    x=[]
    y=[]
    z=[]
    
    data0 = np.genfromtxt('data0.txt', delimiter=',', dtype=float, usecols=np.arange(0,3))
    for row in data0:
        x.append(row[0])
        y.append(row[1])
        z.append(row[2])
    
        print(x)
        print(y)
        print(z)
    

    因此,a)我们在附图中给出的数据文件和b)程序(myFile定义在哪里?)有一些不一致之处 .

    我创建了一个示例 data0.txt 文件:

    -0.3,-1.1,1.36
    -1.1,-2.45,2.7
    -1.7,-4.4,5,5
    0,0,0
    

    Note: I 've removed all leading whitespace, so everything that' s数字看起来像一个数字 .

    我得到了这些结果

    [-0.29999999999999999, -1.1000000000000001, -1.7, 0.0]
    [-1.1000000000000001, -2.4500000000000002, -4.4000000000000004, 0.0]
    [1.3600000000000001, 2.7000000000000002, 5.0, 0.0]
    

相关问题