Reputation: 33
I am reading in a text file and extracting values to display the longitude but from the text file, it is a negative value and need for it to be positive.
A sample of the text file that I have, in the format of (DDDMMSS.SS), named coordinates.txt:
Longitude : -0780417.04
Basically, it needs 359 added to the first 3 numbers (DDD or degrees), 59 to the next 2 numbers (MM or minutes) and 60.00 to the last 4 numbers (SS.SS or seconds).
Note : each split of numbers is a negative value
The desired output is:
281 55 43.0
The code that I have currently is:
with open('coordinates.txt', 'r'): as f:
for line in f:
header = line.split(':')[0]
if 'Longitude' in header:
longitude = line.split(':')[1].strip()[1:4] + " " + line.split(':')[1].strip()[4:6] + " " + line.split(':')[1].strip()[6:10]
print longitude
How would I go about adding those additions to my current code?
Upvotes: 0
Views: 3220
Reputation: 15310
First, pull the value into a variable. Leave it as a string:
key,value = line.split(':')
Next, perform your check. I don't know how you handle positive longitudes. I'm assuming you ignore them:
if key == 'Longitude' and value.strip().startswith('-'):
Next, disassemble the string into variables:
neglong = value.strip()[1:]
ddd = int(neglong[0:3])
mm = int(neglong[3:5])
ss_ss = float(neglong[5:])
Then do your math on the parts, and re-assemble however you like.
Upvotes: 1
Reputation: 7293
x = line.split(':')[1].strip()
first = int(x[1:4]) + 359
second = int(x[4:6]) + 59
third = float(x[6:10]) + 60.0
print(first, second, third)
Upvotes: 0