Dive Into Python-Chapter 5. Objects and Object-Orientation
Số trang: 32
Loại file: pdf
Dung lượng: 0.00 B
Lượt xem: 11
Lượt tải: 0
Xem trước 4 trang đầu tiên của tài liệu này:
Thông tin tài liệu:
Tham khảo tài liệu dive into python-chapter 5. objects and object-orientation, công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả
Nội dung trích xuất từ tài liệu:
Dive Into Python-Chapter 5. Objects and Object-OrientationChapter 5. Objects and Object-OrientationThis chapter, and pretty much every chapter after this, deals with object-oriented Python programming.5.1. Diving InHere is a complete, working Python program. Read the doc strings ofthe module, the classes, and the functions to get an overview of what thisprogram does and how it works. As usual, dont worry about the stuff youdont understand; thats what the rest of the chapter is for.Example 5.1. fileinfo.pyIf you have not already done so, you can download this and other examplesused in this book.Framework for getting filetype-specificmetadata.Instantiate appropriate class with filename.Returned object acts like adictionary, with key-value pairs for each piece ofmetadata. import fileinfo info =fileinfo.MP3FileInfo(/music/ap/mahadeva.mp3) print \n.join([%s=%s % (k, v) for k, v ininfo.items()])Or use listDirectory function to get info on allfiles in a directory. for info infileinfo.listDirectory(/music/ap/, [.mp3]): ...Framework can be extended by adding classes forparticular file types, e.g.HTMLFileInfo, MPGFileInfo, DOCFileInfo. Each classis completely responsible forparsing its files appropriately; see MP3FileInfofor example.import osimport sysfrom UserDict import UserDictdef stripnulls(data): strip whitespace and nulls return data.replace( 0, ).strip()class FileInfo(UserDict): store file metadata def __init__(self, filename=None): UserDict.__init__(self) self[name] = filenameclass MP3FileInfo(FileInfo): store ID3v1.0 MP3 tags 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): parse ID3v1.0 tags from MP3 file self.clear() try: fsock = open(filename, rb, 0) try: fsock.seek(-128, 2) tagdata = fsock.read(128) finally: fsock.close() if tagdata[:3] == TAG: for tag, (start, end, parseFunc) inself.tagDataMap.items(): self[tag] =parseFunc(tagdata[start:end]) except IOError: pass def __setitem__(self, key, item): if key == name and item: self.__parse(item) FileInfo.__setitem__(self, key, item)def listDirectory(directory, fileExtList): get list of file info objects for files ofparticular extensions fileList = [os.path.normcase(f) for f in os.listdir(directory)] fileList = [os.path.join(directory, f) for f in fileList if os.path.splitext(f)[1] infileExtList] def getFileInfoClass(filename,module=sys.modules[FileInfo.__module__]): get file info class from filenameextension subclass = %sFileInfo %os.path.splitext(filename)[1].upper()[1:] return hasattr(module, subclass) andgetattr(module, subclass) or FileInfo return [getFileInfoClass(f)(f) for f infileList]if __name__ == __main__: for info in listDirectory(/music/_singles/,[.mp3]): print .join([%s=%s % (k, v) for k, vin info.items()]) print This programs output depends on the files on your hard drive. To get meaningful output, youll need to change the directory path to point to a directory of MP3 files on your own machine.This is the output I got on my machine. Your output will be different, unless,by some startling coincidence, you share my exact taste in music.album=artist=Ghost in the Machinetitle=A Time Long Forgotten (Conceptgenre=31name=/music/_singles/a_time_long_forgotten_con.mp3year=1999comment=http://mp3.com/ghostmachinealbum=Rave Mixartist=***DJ MARY-JANE***title=HELLRAISER****Trance from Hellgenre=31name=/music/_singles/hellraiser.mp3year=2000comment=http://mp3.com/DJMARYJANEalbum=Rave Mixartist=***DJ MARY-JANE***title=KAIRO****THE BEST GOAgenre=31name=/music/_singles/kairo.mp3year=2000comment=http://mp3.com/DJMARYJANEalbum=Journeysartist=Masters of Balancetitle=Long Way Homegenre=31name=/music/_singles/long_way_home1.mp3year=2000comment=http://mp3.com/MastersofBalanalbum=artist=The Cynic Projecttitle=Sidewindergenre=18name=/music/_singles/sidewinder.mp3year=2000comment=http://mp3.com/cynicprojectalbum=Digitosis@128kartist=VXpandedtitle=Spinninggenre=255name=/music/_singles/spinning.mp3year=2000comment=http://mp3.com/artists/95/vxp5.2. Importing Modules Using from module importPython has two way ...
Nội dung trích xuất từ tài liệu:
Dive Into Python-Chapter 5. Objects and Object-OrientationChapter 5. Objects and Object-OrientationThis chapter, and pretty much every chapter after this, deals with object-oriented Python programming.5.1. Diving InHere is a complete, working Python program. Read the doc strings ofthe module, the classes, and the functions to get an overview of what thisprogram does and how it works. As usual, dont worry about the stuff youdont understand; thats what the rest of the chapter is for.Example 5.1. fileinfo.pyIf you have not already done so, you can download this and other examplesused in this book.Framework for getting filetype-specificmetadata.Instantiate appropriate class with filename.Returned object acts like adictionary, with key-value pairs for each piece ofmetadata. import fileinfo info =fileinfo.MP3FileInfo(/music/ap/mahadeva.mp3) print \n.join([%s=%s % (k, v) for k, v ininfo.items()])Or use listDirectory function to get info on allfiles in a directory. for info infileinfo.listDirectory(/music/ap/, [.mp3]): ...Framework can be extended by adding classes forparticular file types, e.g.HTMLFileInfo, MPGFileInfo, DOCFileInfo. Each classis completely responsible forparsing its files appropriately; see MP3FileInfofor example.import osimport sysfrom UserDict import UserDictdef stripnulls(data): strip whitespace and nulls return data.replace( 0, ).strip()class FileInfo(UserDict): store file metadata def __init__(self, filename=None): UserDict.__init__(self) self[name] = filenameclass MP3FileInfo(FileInfo): store ID3v1.0 MP3 tags 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): parse ID3v1.0 tags from MP3 file self.clear() try: fsock = open(filename, rb, 0) try: fsock.seek(-128, 2) tagdata = fsock.read(128) finally: fsock.close() if tagdata[:3] == TAG: for tag, (start, end, parseFunc) inself.tagDataMap.items(): self[tag] =parseFunc(tagdata[start:end]) except IOError: pass def __setitem__(self, key, item): if key == name and item: self.__parse(item) FileInfo.__setitem__(self, key, item)def listDirectory(directory, fileExtList): get list of file info objects for files ofparticular extensions fileList = [os.path.normcase(f) for f in os.listdir(directory)] fileList = [os.path.join(directory, f) for f in fileList if os.path.splitext(f)[1] infileExtList] def getFileInfoClass(filename,module=sys.modules[FileInfo.__module__]): get file info class from filenameextension subclass = %sFileInfo %os.path.splitext(filename)[1].upper()[1:] return hasattr(module, subclass) andgetattr(module, subclass) or FileInfo return [getFileInfoClass(f)(f) for f infileList]if __name__ == __main__: for info in listDirectory(/music/_singles/,[.mp3]): print .join([%s=%s % (k, v) for k, vin info.items()]) print This programs output depends on the files on your hard drive. To get meaningful output, youll need to change the directory path to point to a directory of MP3 files on your own machine.This is the output I got on my machine. Your output will be different, unless,by some startling coincidence, you share my exact taste in music.album=artist=Ghost in the Machinetitle=A Time Long Forgotten (Conceptgenre=31name=/music/_singles/a_time_long_forgotten_con.mp3year=1999comment=http://mp3.com/ghostmachinealbum=Rave Mixartist=***DJ MARY-JANE***title=HELLRAISER****Trance from Hellgenre=31name=/music/_singles/hellraiser.mp3year=2000comment=http://mp3.com/DJMARYJANEalbum=Rave Mixartist=***DJ MARY-JANE***title=KAIRO****THE BEST GOAgenre=31name=/music/_singles/kairo.mp3year=2000comment=http://mp3.com/DJMARYJANEalbum=Journeysartist=Masters of Balancetitle=Long Way Homegenre=31name=/music/_singles/long_way_home1.mp3year=2000comment=http://mp3.com/MastersofBalanalbum=artist=The Cynic Projecttitle=Sidewindergenre=18name=/music/_singles/sidewinder.mp3year=2000comment=http://mp3.com/cynicprojectalbum=Digitosis@128kartist=VXpandedtitle=Spinninggenre=255name=/music/_singles/spinning.mp3year=2000comment=http://mp3.com/artists/95/vxp5.2. Importing Modules Using from module importPython has two way ...
Tìm kiếm theo từ khóa liên quan:
thủ thuật máy tính công nghệ thông tin quản trị mạng tin học computer networkTài liệu liên quan:
-
52 trang 434 1 0
-
24 trang 359 1 0
-
Top 10 mẹo 'đơn giản nhưng hữu ích' trong nhiếp ảnh
11 trang 321 0 0 -
Làm việc với Read Only Domain Controllers
20 trang 312 0 0 -
74 trang 304 0 0
-
96 trang 299 0 0
-
Báo cáo thực tập thực tế: Nghiên cứu và xây dựng website bằng Wordpress
24 trang 292 0 0 -
Đồ án tốt nghiệp: Xây dựng ứng dụng di động android quản lý khách hàng cắt tóc
81 trang 286 0 0 -
EBay - Internet và câu chuyện thần kỳ: Phần 1
143 trang 277 0 0 -
Tài liệu hướng dẫn sử dụng thư điện tử tài nguyên và môi trường
72 trang 270 0 0