Reputation: 1
I have a text file:
1; (2,2); (3,3); (3,6); (4,8)
2; (2,1); (3,1); (4,1)
3; (6,2); (4,3); (3,1); (1,1)
4; (2,8); (3,8); (3,6); (4,2); (6,0)
5; (0,0); (3,3); (3,6); (4,2)
6; (1,1); (3,9)
My task is to convert each line into a tuple to calculate their length (I have the function for this made already. My problem is that I don't know how to read it line by line instead of column by column.
Here is my code that I have so far but I dont know what to do next
with open('polyline.txt') as poly:
for line in poly:
temp_line = line.split(';')
temp_line = list(map(lambda s: s.strip(), temp_line)) # Removes '\n' from each line
poly_tups = temp_line[1:]
print(poly_tups)
Which returns:
['(2,2)', '(3,3)', '(3,6)', '(4,8)']
['(2,1)', '(3,1)', '(4,1)']
['(6,2)', '(4,3)', '(3,1)', '(1,1)']
['(2,8)', '(3,8)', '(3,6)', '(4,2)', '(6,0)']
['(0,0)', '(3,3)', '(3,6)', '(4,2)']
['(1,1)', '(3,9)']
but 'poly_tups' is now only = ['(1,1)', '(3,9)']
How can I form these into individual rows of tuples (left to right)? Think I have spent so much time looking that my mind has turned to mush.
EDIT: Appears I am confusing contributors with my intentions.
These ['(1,1)', '(3,9)'] are coordinates, so my task is to calculate the length of each line using these coordinates with (1,1) & (3,9) being (x,y).
Here is the function I have made
def polyline_length(tuple):
#This function calculates the length of a polyline
# Coordinates = x & y
x, y = zip(*tuple)
for i in range(len(tuple)):
length = math.sqrt((x[i-1]-x[i])**2+(y[i-1]-y[i]**2))
return length
So I need to be able to add each row to this function to return its length.
Upvotes: 0
Views: 261
Reputation: 11
I am not sure if I understand correctly and i would have made this a comment instead (if only my reputation had allowed it), but do you mean to accumulate the lines?
result= []
with open('polyline.txt') as poly:
for line in poly:
temp_line = line.split(';')
temp_line = list(map(lambda s: s.strip(), temp_line)) # Removes '\n' from each line
poly_tups = temp_line[1:]
result.append(poly_tups)
print(result)
Upvotes: 0
Reputation: 1
I didn't understand completely what you ask but I assume you are trying to get every list's length. Can you check my code, if it doesn't help, please let me know
with open('polyline.txt') as poly:
total = 0
for line in poly:
temp_line = line.split(';')
temp_line = list(map(lambda s: s.strip(), temp_line)) # Removes '\n' from each line
poly_tups = temp_line[1:]
print(poly_tups)
if (len(poly_tups)) > 0:
print(len(poly_tups))
total += len(poly_tups)
print("Total : " , total)
Upvotes: 0