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

如何使用python函数从文本文件导入坐标来计算距离,python,Python,将以下数据保存在名为coordinates.txt的文件中 A,0,0;B,3,4 C,4,7;D,2,9 E,8,2;F,0,6 文件的每一行包含一个点的名称及其X-Y坐标、分号,然后是第二个点的名称及其X-Y坐标,格式如下: :X1,Y1;:X2,Y2 编写脚本,使用以下公式计算距离和城市街区距离: distance = math.sqrt((x1 - x2)**2 + (y1 - y2)**2) City Block Distance = |(X1-X2)|+|(Y1-Y2)| 因此

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

A,0,0;B,3,4
C,4,7;D,2,9
E,8,2;F,0,6
文件的每一行包含一个点的名称及其X-Y坐标、分号,然后是第二个点的名称及其X-Y坐标,格式如下: :X1,Y1;: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 从C4,7到D2,9:实际距离2.828;城市街区距离4 从e8,2到f0,6:实际距离8.944;城市街区距离12。 我曾尝试从excel导入数据,但我是新手,因此不太知道如何实现此目的。

假设您的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))