我在python 3中編寫了一個程序,它從圖像中提取元數據,並用這些信息處理多個事情。其中一個特點是它將從元數據中提取GPS座標,並使用谷歌地圖的靜態API來繪製位置地圖。如何使python代碼更清潔,優化和高效?
一切工作正常,但我寫了這個非常混亂的代碼,從找到的數據中提取座標。我如何清理這些代碼使其更有效率?我也很感謝編寫更好代碼的任何提示。
在此先感謝。
這裏的輸入數據的一個例子:(縮短爲節省空間)
EXIF BrightnessValue: 10
EXIF ColorSpace: sRGB
EXIF ComponentsConfiguration: YCbCr
EXIF Contrast: Normal
EXIF CustomRendered: Normal
EXIF DateTimeDigitized: 2006:10:11 09:37:52
EXIF DateTimeOriginal: 2006:10:11 09:37:52
EXIF DigitalZoomRatio: 0
EXIF ExifImageLength: 768
EXIF ExifImageWidth: 1024
EXIF ExifVersion: 0221
EXIF ExposureBiasValue: 0
EXIF ExposureMode: Auto Exposure
EXIF ExposureProgram: Aperture Priority
EXIF ExposureTime: 1/800
EXIF FNumber: 71/10
EXIF Flash: Flash did not fire, compulsory flash mode
GPS GPSAltitude: 0
GPS GPSAltitudeRef: 0
GPS GPSLatitude: [33, 51, 2191/100]
GPS GPSLatitudeRef: S
GPS GPSLongitude: [151, 13, 1173/100]
GPS GPSLongitudeRef: E
GPS GPSVersionID: [0, 0, 2, 2]
Image Artist:
Image Copyright:
Image DateTime: 2006:10:11 09:37:52
Image ExifOffset: 346
Image GPSInfo: 946
Image ImageDescription: KONICA MINOLTA DIGITAL CAMERA
Image Make: Konica Minolta Camera, Inc.
Image Model: DiMAGE A2
Image Orientation: Horizontal (normal)
這裏是我的代碼做(輸出):
['33', '51', '2191/100', 'S', '151', '13', '1173/100', 'E']
它提取GPSLatitude ,GPSLatitudeRef,GPSLongitude和GPSLongitudeRef,並按照上述順序將它們分配到單個列表。 (順序很重要,因爲其他功能依賴此列表的順序)
代碼段:
def coordinates_extractor():
out = []
lat1 = []
lon1 = []
lat2 = []
lon2 = []
lat3 = []
lon3 = []
lat4 = []
lon4 = []
ALL = []
for tag in tags.keys():
if tag not in ("JPEGThumbnail", "TIFFThumbnail", "EXIF MakerNote"):
out += [("%s: %s" % (tag, tags[tag]))]
out = sorted(out)
for i in out:
if "GPSLatitudeRef:" in i:
lat1 += [i]
if "GPSLatitude:" in i:
lat1 += [i]
for i in out:
if "GPSLongitudeRef:" in i:
lon1 += [i]
if "GPSLongitude:" in i:
lon1 += [i]
for i in lat1:
lat2 += i.split()
del lat2[0]
del lat2[0]
del lat2[3]
del lat2[3]
for i in lat2:
if "[" in i:
lat3 += [i.replace("[", "")]
continue
if "]" not in i:
lat3 += [i]
if "]" in i:
lat3 += [i.replace("]", "")]
for i in lat3:
if "," in i:
lat4 += [i.replace(",", "")]
if "," not in i:
lat4 += [i]
for i in lon1:
lon2 += i.split()
del lon2[0]
del lon2[0]
del lon2[3]
del lon2[3]
for i in lon2:
if "[" in i:
lon3 += [i.replace("[", "")]
continue
if "]" not in i:
lon3 += [i]
if "]" in i:
lon3 += [i.replace("]", "")]
for i in lon3:
if "," in i:
lon4 += [i.replace(",", "")]
if "," not in i:
lon4 += [i]
LATANDLONG = lat4 + lon4
return LATANDLONG
有關改進功能代碼的問題最適合[代碼評論](http://codereview.stackexchange.com/)。 – TigerhawkT3