Reputation: 9
I have to calculate the length of lines that are defined by coordinates in a text file.
In the text file coordinates are written like this:
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);
and a few more lines.
I'm not sure how to do this. I started with trying to strip the id (first number) and strip parentheses. Stripping the id did work, but .strip
for parentheses does absolutely nothing.
with open('polyline.txt','r') as f:
data = f.readlines()
for line in data:
data=line.strip("()")
data=line[3:]
print data
Upvotes: 1
Views: 1301
Reputation: 52133
>>> 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
Note that this gives you the distance between adjacent coordinates in each list.
Upvotes: 2
Reputation: 955
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)
Upvotes: 0