Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1792724
  • 博文数量: 335
  • 博客积分: 4690
  • 博客等级: 上校
  • 技术积分: 4341
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-08 21:38
个人简介

无聊之人--除了技术,还是技术,你懂得

文章分类

全部博文(335)

文章存档

2016年(29)

2015年(18)

2014年(7)

2013年(86)

2012年(90)

2011年(105)

分类: Python/Ruby

2011-07-01 23:33:10

Chapter 5. Objects and Object-Orientation

This chapter, and pretty much every chapter after this, deals with object-oriented Python programming.

这章以及后面的每章都讲讨论Python中的面向对象编程。

5.1. Diving In

Here is a complete, working Python program. Read the doc strings of the module, the classes, and the functions to get an overview of what this program does and how it works. As usual, don't worry about the stuff you don't understand; that's what the rest of the chapter is for.

这章是python中复杂有用的一章。通过阅读moduleclass,以及functiondoc string 来获得对整个程序的功能以及它如何起作用的大致理解。通常,对于你不理解东西你不必太担心,这将是本章接下来将要讲述的。

Example 5.1. fileinfo.py

5.1 fileinfo.py

If you have not already done so, you can  used in this book.

如果你没有获得代码,你可以下载书中本章以及其它章节的代码。

  1. """Framework for getting filetype-specific metadata.
  2.  
  3. Instantiate appropriate class with filename. Returned object acts like a
  4. dictionary, with key-value pairs for each piece of metadata.
  5.     import fileinfo
  6.     info = fileinfo.MP3FileInfo("/music/ap/mahadeva.mp3")
  7.     print "\\n".join(["%s=%s" % (k, v) for k, v in info.items()])
  8.  
  9. Or use listDirectory function to get info on all files in a directory.
  10.     for info in fileinfo.listDirectory("/music/ap/", [".mp3"]):
  11.         ...
  12.  
  13. Framework can be extended by adding classes for particular file types, e.g.
  14. HTMLFileInfo, MPGFileInfo, DOCFileInfo. Each class is completely responsible for
  15. parsing its files appropriately; see MP3FileInfo for example.
  16. """
  17. import os
  18. import sys
  19. from UserDict import UserDict
  20.  
  21. def stripnulls(data):
  22.     "strip whitespace and nulls"
  23.     return data.replace("\00", "").strip()
  24.  
  25. class FileInfo(UserDict):
  26.     "store file metadata"
  27.     def __init__(self, filename=None):
  28.         UserDict.__init__(self)
  29.         self["name"] = filename
  30.  
  31. class MP3FileInfo(FileInfo):
  32.     "store ID3v1.0 MP3 tags"
  33.     tagDataMap = {"title" : ( 3, 33, stripnulls),
  34.                   "artist" : ( 33, 63, stripnulls),
  35.                   "album" : ( 63, 93, stripnulls),
  36.                   "year" : ( 93, 97, stripnulls),
  37.                   "comment" : ( 97, 126, stripnulls),
  38.                   "genre" : (127, 128, ord)}
  39.  
  40.     def __parse(self, filename):
  41.         "parse ID3v1.0 tags from MP3 file"
  42.         self.clear()
  43.         try:
  44.             fsock = open(filename, "rb", 0)
  45.             try:
  46.                 fsock.seek(-128, 2)
  47.                 tagdata = fsock.read(128)
  48.             finally:
  49.                 fsock.close()
  50.             if tagdata[:3] == "TAG":
  51.                 for tag, (start, end, parseFunc) in self.tagDataMap.items():
  52.                     self[tag] = parseFunc(tagdata[start:end])
  53.         except IOError:
  54.             pass
  55.  
  56.     def __setitem__(self, key, item):
  57.         if key == "name" and item:
  58.             self.__parse(item)
  59.         FileInfo.__setitem__(self, key, item)
  60.  
  61. def listDirectory(directory, fileExtList):
  62.     "get list of file info objects for files of particular extensions"
  63.     fileList = [os.path.normcase(f)
  64.                 for f in os.listdir(directory)]
  65.     fileList = [os.path.join(directory, f)
  66.                for f in fileList
  67.                 if os.path.splitext(f)[1] in fileExtList]
  68.     def getFileInfoClass(filename, module=sys.modules[FileInfo.__module__]):
  69.         "get file info class from filename extension"
  70.         subclass = "%sFileInfo" % os.path.splitext(filename)[1].upper()[1:]
  71.         return hasattr(module, subclass) and getattr(module, subclass) or FileInfo
  72.     return [getFileInfoClass(f)(f) for f in fileList]
  73.  
  74. if __name__ == "__main__":
  75.     for info in listDirectory("/music/_singles/", [".mp3"]):
  76.         print "\n".join(["%s=%s" % (k, v) for k, v in info.items()])
  77.         print

1

This program's output depends on the files on your hard drive. To get meaningful output, you'll need to change the directory path to point to a directory of MP3 files on your own machine.

程序的输出依赖于你硬盘上面的文件。为了获得有意义的输出,你需要修改目录路径来指向你自己机器上面MP3文件的目录

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.

下面是在我的机器上面获得的输出,你的输出可能会不同,除非某些惊人的巧合,我们具有相同的音乐爱好。

  1. album=
  2. artist=Ghost in the Machine
  3. title=A Time Long Forgotten (Concept
  4. genre=31
  5. name=/music/_singles/a_time_long_forgotten_con.mp3
  6. year=1999
  7. comment=http://mp3.com/ghostmachine
  8.  
  9. album=Rave Mix
  10. artist=***DJ MARY-JANE***
  11. title=HELLRAISER****Trance from Hell
  12. genre=31
  13. name=/music/_singles/hellraiser.mp3
  14. year=2000
  15. comment=http://mp3.com/DJMARYJANE
  16.  
  17. album=Rave Mix
  18. artist=***DJ MARY-JANE***
  19. title=KAIRO****THE BEST GOA
  20. genre=31
  21. name=/music/_singles/kairo.mp3
  22. year=2000
  23. comment=http://mp3.com/DJMARYJANE
  24.  
  25. album=Journeys
  26. artist=Masters of Balance
  27. title=Long Way Home
  28. genre=31
  29. name=/music/_singles/long_way_home1.mp3
  30. year=2000
  31. comment=http://mp3.com/MastersofBalan
  32.  
  33. album=
  34. artist=The Cynic Project
  35. title=Sidewinder
  36. genre=18
  37. name=/music/_singles/sidewinder.mp3
  38. year=2000
  39. comment=http://mp3.com/cynicproject
  40.  
  41. album=Digitosis@128k
  42. artist=VXpanded
  43. title=Spinning
  44. genre=255
  45. name=/music/_singles/spinning.mp3
  46. year=2000
  47. comment=http://mp3.com/artists/95/vxp
阅读(1034) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~