本文目录导读:

- Python - 度分秒(DMS) 转 十进制度(DD)
- Python - 十进制度(DD) 转 度分秒(DMS)
- JavaScript - 坐标格式转换
- Bash/Python - 批量转换CSV文件坐标
- 在线批量转换(Python)
- 使用方法
- 注意事项
Python - 度分秒(DMS) 转 十进制度(DD)
def dms_to_dd(dms_string):
"""
将度分秒格式转换为十进制度
示例输入: "40°26'46.4\"N" 或 "116°40'12.8\"E"
"""
import re
# 正则匹配度分秒和方向
pattern = r'(\d+)[°\s](\d+)[\'\s](\d+(?:\.\d+)?)[\"\s]?([NSEW])?'
match = re.search(pattern, dms_string)
if not match:
raise ValueError("无效的度分秒格式")
degrees = float(match.group(1))
minutes = float(match.group(2))
seconds = float(match.group(3))
direction = match.group(4)
# 转换为十进制度
decimal = degrees + minutes/60 + seconds/3600
# 处理南纬和西经为负数
if direction in ['S', 'W']:
decimal = -decimal
return decimal
# 使用示例
print(dms_to_dd("40°26'46.4\"N")) # 输出: 40.4462...
print(dms_to_dd("116°40'12.8\"E")) # 输出: 116.6702...
Python - 十进制度(DD) 转 度分秒(DMS)
def dd_to_dms(decimal_degrees):
"""
将十进制度转换为度分秒格式
示例: 40.4462 -> "40°26'46.32\"N"
"""
import math
# 确定方向
direction = 'N' if decimal_degrees >= 0 else 'S'
if abs(decimal_degrees) > 90:
direction = 'E' if decimal_degrees >= 0 else 'W'
decimal_degrees = abs(decimal_degrees)
# 计算度分秒
degrees = int(decimal_degrees)
minutes_float = (decimal_degrees - degrees) * 60
minutes = int(minutes_float)
seconds = (minutes_float - minutes) * 60
return f"{degrees}°{minutes}'{seconds:.2f}\"{direction}"
# 使用示例
print(dd_to_dms(40.4462)) # 输出: 40°26'46.32"N
JavaScript - 坐标格式转换
function convertCoordinate(coord, fromFormat, toFormat) {
/**
* fromFormat/toFormat: 'DMS' (度分秒) 或 'DD' (十进制度)
*/
function dmsToDD(dms) {
// 处理 "40°26'46.4"N 格式
const matches = dms.match(/(\d+)°(\d+)'(\d+\.?\d*)"?([NSEW])/);
if (!matches) return NaN;
let dd = parseFloat(matches[1]) +
parseFloat(matches[2])/60 +
parseFloat(matches[3])/3600;
if (matches[4] === 'S' || matches[4] === 'W') dd = -dd;
return dd;
}
function ddToDMS(dd) {
let direction = dd >= 0 ? 'N' : 'S';
dd = Math.abs(dd);
const degrees = Math.floor(dd);
const minutesFloat = (dd - degrees) * 60;
const minutes = Math.floor(minutesFloat);
const seconds = (minutesFloat - minutes) * 60;
return `${degrees}°${minutes}'${seconds.toFixed(2)}"${direction}`;
}
if (fromFormat === 'DMS' && toFormat === 'DD') {
return dmsToDD(coord);
} else if (fromFormat === 'DD' && toFormat === 'DMS') {
return ddToDMS(parseFloat(coord));
}
return '不支持的格式';
}
// 使用示例
console.log(convertCoordinate("40°26'46.4\"N", 'DMS', 'DD')); // 40.4462...
console.log(convertCoordinate(40.4462, 'DD', 'DMS')); // 40°26'46.32"N
Bash/Python - 批量转换CSV文件坐标
import csv
import sys
def convert_csv_coordinates(input_file, output_file):
"""
批量转换CSV文件中的坐标(假设第3列和第4列是经纬度)
"""
with open(input_file, 'r') as infile, open(output_file, 'w', newline='') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
# 写入表头
header = next(reader)
header.extend(['lat_dd', 'lon_dd'])
writer.writerow(header)
for row in reader:
try:
# 假设第3列是纬度DMS,第4列是经度DMS
lat_dd = dms_to_dd(row[2])
lon_dd = dms_to_dd(row[3])
row.extend([lat_dd, lon_dd])
writer.writerow(row)
except ValueError as e:
print(f"跳过无效行: {row}, 错误: {e}")
# 命令行调用
if __name__ == "__main__":
if len(sys.argv) != 3:
print("使用方法: python convert.py 输入文件.csv 输出文件.csv")
else:
convert_csv_coordinates(sys.argv[1], sys.argv[2])
在线批量转换(Python)
import re
import json
def batch_convert(coordinates_list, input_format='DMS', output_format='DD'):
"""
批量转换多个坐标
"""
results = []
for coord in coordinates_list:
try:
if input_format == 'DMS' and output_format == 'DD':
converted = dms_to_dd(coord)
elif input_format == 'DD' and output_format == 'DMS':
converted = dd_to_dms(float(coord))
results.append(converted)
except Exception as e:
results.append(f"错误: {e}")
return results
# 使用示例
coords = ["40°26'46.4\"N", "116°40'12.8\"E", "31°14'5.2\"N"]
converted = batch_convert(coords)
print(converted)
使用方法
- 保存脚本到
.py或.html文件 - 运行脚本:
- Python:
python 脚本名.py - JavaScript: 在浏览器控制台或Node.js中运行
- Python:
- 修改输入为你的实际坐标格式
注意事项
- 确保坐标格式与你使用的转换函数匹配
- 处理异常情况(无效格式、超出范围等)
- 根据实际情况调整正则表达式匹配规则
- 批量转换时注意文件编码
如果你有特定的坐标格式或需要特定语言的实现,请提供更多细节,我可以给出更针对性的解决方案。