Python執行個體擷取mp3檔案的tag資訊

來源:互聯網
上載者:User
下面利用一個python的執行個體程式,來學習python。這個程式的目的就是分析出所有MP3檔案的Tag資訊並輸出。

import os # 匯入os模組,提供檔案路徑,列出檔案等方法import sys # 匯入sys模組,使用sys.modules擷取模組中的所有內容,類似反射的功能from UserDict import UserDict # 這個表示從UserDict類中匯入UserDict,類似於Java中的 import UserDict.UserDict  def stripnulls(data):    "一個Null 字元串的處理函數將所有00位元組的內容替換為空白字元,病將前後的Null 字元串去掉"    # Python中的strip用於去除字串的首尾字元,同理,lstrip用於去除左邊的字元,rstrip用於去除右邊的字元。    return data.replace("\00", "").strip()  class FileInfo(UserDict):    '''檔案基類,隱藏檔的檔案名稱,繼承自UserDict(儲存key-value的一個類,可以重寫__setitem__,__getitem__方法,    就可以使用[])'''    # self是定義時使用,使用時不需要,如果沒有參數,則filename預設None,如果有一個參數的話,參數即為filename    def __init__(self, filename=None):        UserDict.__init__(self) # 初始化父類        self["name"] = filename # 設定name為 filaname  class MP3FileInfo(FileInfo):    "MP3檔案的資訊類,用於分析MP3檔案和儲存資訊"    # tagDataMap 用於儲存MP3的Tag資訊分別所在位置,( key : 開始位置,結束位置, 處理函數),    # stripnulls表示最開始定義的函數    tagDataMap = {"title" : ( 3, 33, stripnulls),    "artist" : ( 33, 63, stripnulls),    "album" : ( 63, 93, stripnulls),    "year" : ( 93, 97, stripnulls),    "comment" : ( 97, 126, stripnulls),    "genre" : (127, 128, ord)}          def __parse(self, filename): # 解析MP3檔案        self.clear()        try:            fsock = open(filename, "rb", 0) # 開啟檔案            try:                # 設定檔案讀取的指標位置, seek第二個參數,2表示從檔案結尾作為參考點,                # -128表示還有128位元組結尾的點,0表示檔案開頭做參考點,1表示當前位置做參考點                fsock.seek(-128, 2)                tagdata = fsock.read(128) # 讀取128位元組的資料            finally:                fsock.close() # 關閉檔案,注意在finally中,出錯也需要關閉檔案控制代碼            if tagdata[:3] == "TAG": # 判斷是否是有效含Tag的MP3檔案                # 迴圈取出Tag資訊位置資訊, 如3, 33, stripnulls,並依次賦給start, end, parseFunc                for tag, (start, end, parseFunc) in self.tagDataMap.items():                    # tagdata[start:end]讀出start到end的位元組,使用parseFunc處理這些內容                    self[tag] = parseFunc(tagdata[start:end])        except IOError: # 如果出現IOError,則跳過繼續            pass          # 重寫__setitem__方法,上面的self[tag] = parseFunc(tagdata[start:end])就會使用這個方法,    # key為tag,itme為parseFunc(tagdata[start:end])    def __setitem__(self, key, item):        if key == "name" and item: # 如果key是 name,並且 item不為空白            self.__parse(item) # 解析MP3檔案            # problem here,should out of the if            # FileInfo.__setitem__(self, key, item) 如果使用這個縮排就會出現錯誤        # 之前的錯誤點,注意這兒的縮排,無論如何都會儲存key-value,使用FileInfo.__setitem__父類的方法來儲存        FileInfo.__setitem__(self, key, item)              def listDirectory(directory, fileExtList):    "擷取directory目錄下的所有fileExtList格式的檔案,fileExtList是一個列表,可以有多種格式"    fileList = [os.path.normcase(f)        for f in os.listdir(directory)] # 列出所有 directory的檔案    fileList = [os.path.join(directory, f)        for f in fileList        # 過濾檔案,滿足fileExtList內的一種格式。os.path.splitext將檔案分成檔案名稱和副檔名        if os.path.splitext(f)[1] in fileExtList]              # sys.modules[FileInfo.__module__] 擷取FileInfo.__module__模組,其中FileInfo.__module__在此會是 main,    # 如果被別的模組調用的話就不是了,這是為什麼不直接用“main”    def getFileInfoClass(filename, module=sys.modules[FileInfo.__module__]):        "定義一個函數,擷取檔案的資訊"         # 擷取需要用來解析的類,如果是mp3檔案結果為MP3FileInfo,其他為FileInfo        subclass = "%sFileInfo" % os.path.splitext(filename)[1].upper()[1:]        # 返回一個類,注意,返回的是一個“類”。使用getattr擷取moudle模組中的subclass類        return hasattr(module, subclass) and getattr(module, subclass) or FileInfo    # 注意,這句話可能比較難理解, getFileInfoClass(f) (f)為什麼會有兩個(f)呢,上面已經說過getFileInfoClass(f)    # 根據檔案名稱返回一個解析類,這兒是返回就是MP3FileInfo,而第二個(f)就表示對這個類以f初始化MP3FileInfo(f)    return [getFileInfoClass(f) (f) for f in fileList]  if __name__ == "__main__": # main函數,在別的模組中不會允許這裡面的代碼了    for info in listDirectory("E:\\Music", [".mp3"]): # 迴圈擷取E:\\Music檔案夾中所有的mp3檔案的資訊        # 由於MP3FileInfo繼承自FileInfo,FileInfo繼承自UserDict,這個的items()就是擷取key-value集合。        # 使用"%s=%s"格式化輸出,使用"\n".join將所有資訊以換行串連。        print "\n".join(["%s=%s" % (k, v) for k, v in info.items()])        print # 每一個檔案之後,輸出一個空行

結果為:

album=What Are Words - Single

comment=pythontab

name=E:\Music\chris medina - what_are_words.mp3

title=What Are Words

artist=Chris Medina

year=2011

genre=13

album=After the Wedding

comment=pythontab

name=E:\Music\two fathers.mp3

title=Two Fathers

artist=pythontab

year=2010

genre=255


注意:邏輯比較多,代碼不算少,不懂的多看注釋

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.