我必须计算由文本文件中的坐标定义的行的长度。
在文本文件中,坐标的写法如下:
1; (5,2); (3,3); (3,2); (1,0)
2; (4,5); (5,7); (6,8); (8,9)
3; (1,1); (1,2); (1,3)
4; (2,1); (3,2);
还有几行。
我不知道该怎么做。我开始尝试剥离id(第一个数字)和剥离括号。剥离id确实有效,但括号中的.strip
绝对没有。
with open('polyline.txt','r') as f:
data = f.readlines()
for line in data:
data=line.strip("()")
data=line[3:]
print data
答案 0 :(得分:2)
>>> from math import pow, sqrt
>>> def distance(c1, c2):
... return sqrt(pow(c2[0] - c1[0], 2) + pow(c2[1] - c1[1], 2))
>>> distance((3, 1), (3, 2))
1.0
-
>>> import re
>>> with open('polyline.txt','r') as f:
... for line in f:
... coordinates = re.findall(r'\((\d+),(\d+)\)', line)
... coordinates = map(lambda c: map(int, c), coordinates)
... print coordinates
... for i, coordinate in enumerate(coordinates[:-1]):
... print distance(coordinate, coordinates[i + 1]),
... print
[[5, 2], [3, 3], [3, 2], [1, 0]]
2.2360679775 1.0 2.82842712475
[[4, 5], [5, 7], [6, 8], [8, 9]]
2.2360679775 1.41421356237 2.2360679775
[[1, 1], [1, 2], [1, 3]]
1.0 1.0
[[2, 1], [3, 2]]
1.41421356237
请注意,这会为您提供每个列表中相邻坐标之间的距离。
答案 1 :(得分:0)
import re, math
def distance_formula(p1, p2):
return math.sqrt((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2)
lines = []
with open('file.txt', 'rb') as f:
for row in f.read().splitlines():
row = [int(x) for x in re.findall(r'(\d+)', row)]
lines.append(sorted([(row[i + 1], row[i + 2]) for i in range(0, len(row[1:]), 2)]))
for i, line in enumerate(lines):
distance = 0
for c, coordinate in enumerate(line):
distance = distance + distance_formula(coordinate, line[c + 1])
if c + 1 >= len(line) - 1:
break
print 'Line {0} has a length of {1} units'.format(i + 1, distance)