簡體   English   中英

如何使 Python 代碼更簡潔、優化和高效?

[英]How can I make python code cleaner, optimized, and efficient?

我在 python 3 中編寫了一個程序,該程序從圖像中提取元數據並使用此信息執行多項操作。 其中一項功能是它會從元數據中提取 GPS 坐標,並使用谷歌地圖的靜態 API 來繪制位置地圖。

一切正常,但我寫了這個非常凌亂的代碼來從找到的數據中提取坐標。 如何清理此代碼使其更有效? 我也很感激任何編寫更好代碼的提示。

提前致謝。

這是輸入數據的示例:(縮短以節省空間)

    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 : //ptforum.photoolsweb.com/ubbthreads.php?ubb=download&Number=1024&filename=1024-2006_1011_093752.jpg

你可以嘗試這樣的事情。 我包含了一個模擬的 dict 對象,以便在沒有圖像的情況下輕松運行。 您只需要刪除它並將其替換為exifread庫提供的真實tags對象,我相信您正在使用它。

# mock dictionary because I dont have your image
tags = {}
tags['GPS GPSLatitude'] =  [33, 51, 2191/100]
tags['GPS GPSLatitudeRef'] = 'S'
tags['GPS GPSLongitude'] = [151, 13, 1173/100]
tags['GPS GPSLongitudeRef'] = 'E'

out = []
wantedtags = ('GPS GPSLatitude', 'GPS GPSLatitudeRef', 'GPS GPSLongitude', 'GPS GPSLongitudeRef')

for tag in wantedtags:
    try:
        val = tags[tag]
        if isinstance(val, list):
            out.extend(map(str, val))
        else:
            out.append(val)
    except KeyError:
        print('Key %s does not exists' % tag)

print(out)

但需要注意的是,輸出與您的預期輸出完全不同。 原因是文字2191/1001173/100在運行時被評估為除法語句,並且在列表中被視為 python 2 的21 & 11和 python 3 的21.91 & 11.73 。在 python 2 中使用from __future__ import division以獲得更精確的除法結果。

exifread的行為exifread不同? 即它是否以某種其他形式存儲該值以保持小數值而不僅僅是一個普通的舊 int?

我針對我自己的模擬字典運行了你自己的代碼,輸出與我的版本完全相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM