如何使用python函数通过从文本文件导入坐标来计算距离

时间:2019-04-29 09:18:13

标签: python

将以下数据保存在名为axis.txt的文件中。

A,0,0;B,3,4
C,4,7;D,2,9
E,8,2;F,0,6

文件的每一行都包含一个点的名称及其X-Y坐标,一个分号,然后是第二个点的名称及其X-Y坐标,格式为: <Name1>:X1,Y1;<Name2>:X2,Y2;

编写脚本以使用以下公式计算距离和城市街区距离:

distance = math.sqrt((x1 - x2)**2 + (y1 - y2)**2) 
City Block Distance = |(X1-X2)|+|(Y1-Y2)|

因此,脚本的输出变为:

  • 从A(0,0)到B(3,4):实际距离5.000;街区距离7
  • 从C(4,7)到D(2,9):实际距离2.828;街区距离4
  • 从E(8,2)到F(0,6):实际距离8.944;街区距离12。

我曾尝试从excel导入数据,但是我是新手,所以对如何实现此目的没有太多的了解。

1 个答案:

答案 0 :(得分:0)

假设coordinates.txt与Python脚本位于同一目录中:

with open("coordinates.txt", 'r') as coordinates_file:
    for line in coordinates_file:
        # delete trailing new-line character
        line = line.rstrip()
        # unpack points (e.g. "A,0,0")
        point_1, point_2 = line.split(";")
        # name_* is for example "A"; loc*_tmp is a string representation of coords
        name_1, *loc1_tmp = point_1.split(",")
        # change coords to int
        loc1 = [int(loc) for loc in loc1_tmp]
        name_2, *loc2_tmp = point_2.split(",")
        loc2 = [int(loc) for loc in loc2_tmp]
        euclidian_distance = math.sqrt((loc1[0] - loc2[0])**2 + (loc1[1] - loc2[1])**2)
        block_distance = abs(loc1[0] - loc2[0]) + abs(loc1[1] - loc2[1])
        print("The distances between {} and {}:".format(name_1, name_2))
        print("Euclidian distance {}".format(euclidian_distance))
        print("Block distance {}".format(block_distance))