使用Numpy从文本文件中读取点三乘三的坐标吗?

时间:2018-07-25 07:00:11

标签: python numpy

我想使用文本文件中的数据计算角度。 现在,我有一个可以计算角度的python代码。

import numpy as np

a = np.array([27.090, 26.790, 4.920])
b = np.array([26.790, 26.400, 5.740])
c = np.array([27.490, 26.590, 6.370])

ba = a - b
bc = c - b

cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))
angle = np.arccos(cosine_angle)

print np.degrees(angle)

但是我希望此python代码应从文本文件(coord.txt)中获取坐标。因为我在文本文件中有多个坐标,例如

27.090 26.790 4.920
26.790 26.400 5.740
27.490 26.590 6.370 

文本文件的格式为每行x1 y1 z1 x2 y2 z2 x3 y3 z3,并且应给出与每行相对应的角度。

代码应考虑文本文件的坐标并在另一个文本文件中写入角度。

2 个答案:

答案 0 :(得分:1)

import numpy as np
with open(filename) as infile:
    data = [map(float, i.split()) for i in infile.readlines()]
    data = [map(np.array, [j[i:i+3] for i in range(0, len(j), 3)]) for j in data]    

for i in data:
    print i

输出:

[array([ 27.09,  26.79,   4.92]), array([ 26.79,  26.4 ,   5.74]), array([ 27.49,  26.59,   6.37])]
[array([ 1.239,  2.36 ,  4.56 ]), array([ 2.34,  4.56,  6.9 ]), array([ 2.35,  6.98,  9.07])]

根据评论进行编辑

import numpy as np

def getAngle(a, b, c):
    ba = a - b
    bc = c - b
    cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))
    angle = np.arccos(cosine_angle)
    return np.degrees(angle)

with open(filename) as infile:
    data = [map(float, i.split()) for i in infile.readlines()]
    data = [map(np.array, [j[i:i+3] for i in range(0, len(j), 3)]) for j in data]

for i in data:
    a, b, c =  i
    print(getAngle(a, b, c))

答案 1 :(得分:1)

如果您的文本文件是这样的(每行包含三个数据,并由空格分割):

27.090 26.790 4.920
26.790 26.400 5.740
27.490 26.590 6.370

然后您可以尝试以下操作:

import csv
import numpy as np

coord = []
with open("coord.txt", 'r') as f:
    reader = csv.reader(f)
    for line in reader:
        coord.append(line[0].split(' '))

for i, line in enumerate(coord):
    for j, value in enumerate(line):
        coord[i][j] = float(value)

print(coord)