yeyuguo
9/19/2017 - 2:46 AM

经纬度字符转数值.py

#coding:utf-8
import re
def str2geo(string=u'114°52\'59.52"E',numType=True,decimal=5):
    '''
    # pdb.set_trace()
    u'114°52\'59.52"E'
    不返回 度分秒 刻读的
    re.match(r'(.*)(?:[\xb0])(.*)(?:[\'])(.*)(?:[\"])([\w]?)',string)
                 1             2           3            4
    返回 度分秒 刻读的    
    g = re.match(r'(.*)([\xb0])(.*)([\'])(.*)([\"])([\w]?)',string)
                    1      2    3    4    5    6     7
    '''
    string = string.replace(' ','')
    string = string.replace(u' ','')
    number_re = '[\d+]*[.\d+]*'  # 匹配数字
    g = re.match(r'(%s)([\xb0]+)(%s)([\']?)(%s)([\"]?)([\w]?)'%(number_re,number_re,number_re),string)
    group = g.group
    if group().find(group(2)) == 0:
        # 无度数的
        dd = 0
        mm = 0
        ss = 0
    elif group().find(group(4)) == 0:
        # 无分数
        dd = group(1)
        mm = 0
        ss = 0
    elif group().find(group(6)) == 0:
        # 无秒数的
        dd = group(1)
        mm = group(3)
        ss = 0
        pass
    else:
        # 度分秒都有的
        dd = group(1)
        mm = group(3)
        ss = group(5)
    flag = group(7)
    result = float(dd) + float(mm)/60 + float(ss)/3600

    if not numType:
        # 直接返回带 N E 的字符串
        return str(result) + ' ' + flag
    # 返回正负值的经纬度
    result = round(float(dd) + float(mm)/60 + float(ss)/3600,decimal)
    # pdb.set_trace()
    if flag == u'E' or flag == u'N':
        return result
    elif flag == u'W' or flag == u'S':
        return -result

# print str2geo(string=u'114°52.6\'32"E')