Python ephem模块无法识别看似有效的纬度字符串

时间:2015-03-03 21:16:55

标签: python pyephem

我正在尝试使用以下代码计算上升和落日的方位角:

import ephem
import csv
import math

def convert_angle(angle):
    fields = math.modf(angle)
    deg = fields[1]
    min_dec = abs(fields[0]*60)
    min_fields = math.modf(min_dec)
    minu = min_fields[1]
    sec = min_fields[0]*60
    s = '\'{:2.0f}:{:2.0f}:{:2.1f}\''.format(deg,minu,sec)
    return s

sun = ephem.Sun()

with open('locations.txt', 'rb') as csvfile:
    rdrreader = csv.reader(csvfile, delimiter='\t', quotechar='"')
    for row in rdrreader:
        print row[2],row[5],row[6]

        lat = convert_angle(float(row[5]))
        lon = convert_angle(float(row[6]))

        print lat,lon

        obs = ephem.Observer()
        obs.lat = lat       
        obs.lon = lon
        rising = obs.next_rising(sun)
        print('Visual sunrise: %s' % rising)

脚本对我的格式不满意:

ipdb> c
'60:47:31.2' '-161:52:35.5'
> /Users/mmuratet/weather/solar_ephem.py(35)<module>()
     34         obs = ephem.Observer()
3--> 35         obs.lat = lat       
     36         obs.lon = lon
ipdb> s
ValueError: 'your angle string %r does not have the format     [number[:number[:number]]]'
> /Users/mmuratet/weather/solar_ephem.py(35)<module>()
     34         obs = ephem.Observer()
3--> 35         obs.lat = lat       
     36         obs.lon = lon

然而相同的命令在python控制台中使用剪切和粘贴

>>> obs.lat = '60:47:31.2' 
>>> print obs
<ephem.Observer date='2015/3/3 20:00:58' epoch='2000/1/1 12:00:00'     lon=-161:52:35.5 lat=60:47:31.2 elevation=0.0m horizon=0:00:00.0 temp=15.0C pressure=1010.0mBar>

我知道必须有一个简单而明显的解决方案,但我没有看到它。任何建议将不胜感激。

以下是一些数据:

AK      Bethel  PABC    60.791987#N     161.876539#W    60.7919870      -161.876539
AK      Fairbanks/Pedro Dome    PAPD    65.0351238#N    147.5014222#W   65.0351238      -147.5014222

1 个答案:

答案 0 :(得分:1)

看起来你的latlon字符串里面都有单引号,一个在字符串的开头,一个在结尾:

s = '\'{:2.0f}:{:2.0f}:{:2.1f}\''.format(deg,minu,sec)

单引号不是科学家写纬度或经度的方式,因此PyEphem很困惑。尝试构建字符串,而不包含额外的两个字符:

s = '{:2.0f}:{:2.0f}:{:2.1f}'.format(deg,minu,sec)

当它只看到数字和冒号时,PyEphem应该感到高兴!