Dar*_*ech 7 python gps coordinates coordinate-transformation
嗨,我有一个带有一些位置数据的遗留数据库.字段只是带有这样字符串的文本字段0°25'30"S, 91°7'W.有没有一些方法,我可以转换这些两个浮点数为Decimal Latitude和Decimal Longitude?
编辑:
所以一个例子是: 0°25'30"S, 91°7'W- > 0.425,91.116667其中原始单个字段位置产生两个浮点数.
任何帮助非常感谢.
fra*_*xel 18
这种方法可以处理缺少的秒和分钟,我认为正确处理指南针方向:
# -*- coding: latin-1 -*-
def conversion(old):
direction = {'N':1, 'S':-1, 'E': 1, 'W':-1}
new = old.replace(u'°',' ').replace('\'',' ').replace('"',' ')
new = new.split()
new_dir = new.pop()
new.extend([0,0,0])
return (int(new[0])+int(new[1])/60.0+int(new[2])/3600.0) * direction[new_dir]
lat, lon = u'''0°25'30"S, 91°7'W'''.split(', ')
print conversion(lat), conversion(lon)
#Output:
0.425 91.1166666667
Run Code Online (Sandbox Code Playgroud)
这会将您的输入字符串转换为预期的输出。它可以处理不存在的分钟和秒。
\n\n目前,它不考虑北/南、东/西。如果您告诉我您希望如何处理这些问题,我将更新答案。
\n\n# -*- coding: latin-1 -*-\nimport re\n\nPATTERN = re.compile(r"""(?P<lat_deg>\\d+)\xc2\xb0 # Latitude Degrees\n (?:(?P<lat_min>\\d+)\')? # Latitude Minutes (Optional)\n (?:(?P<lat_sec>\\d+)")? # Latitude Seconds (Optional)\n (?P<north_south>[NS]) # North or South\n ,[ ]\n (?P<lon_deg>\\d+)\xc2\xb0 # Longitude Degrees\n (?:(?P<lon_min>\\d+)\')? # Longitude Minutes (Optional)\n (?:(?P<lon_sec>\\d+)")? # Longitude Seconds (Optional)\n (?P<east_west>[EW]) # East or West\n """, re.VERBOSE)\n\nLAT_FIELDS = ("lat_deg", "lat_min", "lat_sec")\nLON_FIELDS = ("lon_deg", "lon_min", "lon_sec")\n\ndef parse_dms_string(s, out_type=float):\n """\n Convert a string of the following form to a tuple of out_type latitude, longitude.\n\n Example input:\n 0\xc2\xb025\'30"S, 91\xc2\xb07\'W\n """\n values = PATTERN.match(s).groupdict()\n\n return tuple(sum(out_type(values[field] or 0) / out_type(60 ** idx) for idx, field in enumerate(field_names)) for field_names in (LAT_FIELDS, LON_FIELDS))\n\n\nINPUT = """0\xc2\xb025\'30"S, 91\xc2\xb07\'W"""\n\nprint parse_dms_string(INPUT) # Prints: (0.42500000000000004, 91.11666666666666)\nRun Code Online (Sandbox Code Playgroud)\n