??xml version="1.0" encoding="utf-8" standalone="yes"?>久久综合狠狠综合久久综青草 ,日韩精品国产精品,亚洲va国产天堂va久久enhttp://www.aygfsteel.com/fhtdy2004/category/39267.htmll验薄Q耐心U篏Q记性不好,记诸文字zh-cnSat, 18 Jun 2011 22:12:50 GMTSat, 18 Jun 2011 22:12:50 GMT60Python学习W记Q二Q?/title><link>http://www.aygfsteel.com/fhtdy2004/archive/2009/08/22/292232.html</link><dc:creator>Frank_Fang</dc:creator><author>Frank_Fang</author><pubDate>Sat, 22 Aug 2009 15:48:00 GMT</pubDate><guid>http://www.aygfsteel.com/fhtdy2004/archive/2009/08/22/292232.html</guid><wfw:comment>http://www.aygfsteel.com/fhtdy2004/comments/292232.html</wfw:comment><comments>http://www.aygfsteel.com/fhtdy2004/archive/2009/08/22/292232.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/fhtdy2004/comments/commentRss/292232.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/fhtdy2004/services/trackbacks/292232.html</trackback:ping><description><![CDATA[<p>python 异常、正则表辑ּ<br /> <a >http://docs.python.org/library/re.html</a><br /> <a >http://docs.python.org/howto/regex.html#regex-howto</a><br /> <br /> ?6.1. 打开一个不存在的文?br /> >>> fsock = open("/notthere", "r")      <br /> Traceback (innermost last):<br />   File "<interactive input>", line 1, in ?<br /> IOError: [Errno 2] No such file or directory: '/notthere'<br /> >>> try:<br /> ...     fsock = open("/notthere")       <br /> ... except IOError:                     <br /> ...     print "The file does not exist, exiting gracefully"<br /> ... print "This line will always print" <br /> The file does not exist, exiting gracefully<br /> This line will always print</p> <p><br /> # Bind the name getpass to the appropriate function<br />   try:<br />       import termios, TERMIOS                     <br />   except ImportError:<br />       try:<br />           import msvcrt                           <br />       except ImportError:<br />           try:<br />               from EasyDialogs import AskPassword <br />           except ImportError:<br />               getpass = default_getpass           <br />           else:                                   <br />               getpass = AskPassword<br />       else:<br />           getpass = win_getpass<br />   else:<br />       getpass = unix_getpass</p> <p> </p> <p>?6.10. 遍历 dictionary<br /> >>> import os<br /> >>> for k, v in os.environ.items():       <br /> ...     print "%s=%s" % (k, v)<br /> USERPROFILE=C:\Documents and Settings\mpilgrim<br /> OS=Windows_NT<br /> COMPUTERNAME=MPILGRIM<br /> USERNAME=mpilgrim</p> <p>[...?..]<br /> >>> print "\n".join(["%s=%s" % (k, v)<br /> ...     for k, v in os.environ.items()]) <br /> USERPROFILE=C:\Documents and Settings\mpilgrim<br /> OS=Windows_NT<br /> COMPUTERNAME=MPILGRIM</p> <p> </p> <p>?6.13. 使用 sys.modules<br /> >>> import fileinfo         <br /> >>> print '\n'.join(sys.modules.keys())<br /> win32api<br /> os.path<br /> os<br /> fileinfo<br /> exceptions</p> <p>>>> fileinfo<br /> <module 'fileinfo' from 'fileinfo.pyc'><br /> >>> sys.modules["fileinfo"] <br /> <module 'fileinfo' from 'fileinfo.pyc'></p> <p><br /> 下面的例子将展示通过l合使用 __module__ cd性和 sys.modules dictionary 来获取已知类所在的模块?</p> <p>?6.14. __module__ cd?<br /> >>> from fileinfo import MP3FileInfo<br /> >>> MP3FileInfo.__module__              <br /> 'fileinfo'<br /> >>> sys.modules[MP3FileInfo.__module__] <br /> <module 'fileinfo' from 'fileinfo.pyc'>  每个 Python c都拥有一个内|的cd?__module__Q它定义了这个类的模块的名字?nbsp; <br />   它?sys.modules 字典复合使用Q你可以得到定义了某个类的模块的引用?nbsp; </p> <p> </p> <p>?6.16. 构造\径名<br /> >>> import os<br /> >>> os.path.join("c:\\music\\ap\\", "mahadeva.mp3")  <br /> 'c:\\music\\ap\\mahadeva.mp3'<br /> >>> os.path.join("c:\\music\\ap", "mahadeva.mp3")   <br /> 'c:\\music\\ap\\mahadeva.mp3'<br /> >>> os.path.expanduser("~")                         <br /> 'c:\\Documents and Settings\\mpilgrim\\My Documents'<br /> >>> os.path.join(os.path.expanduser("~"), "Python") <br /> 'c:\\Documents and Settings\\mpilgrim\\My Documents\\Python'</p> <p> </p> <p>?7.2. 匚w整个单词<br /> >>> s = '100 BROAD'<br /> >>> re.sub('ROAD$', 'RD.', s)<br /> '100 BRD.'<br /> >>> re.sub('\\bROAD$', 'RD.', s)  <br /> '100 BROAD'<br /> >>> re.sub(r'\bROAD$', 'RD.', s)  <br /> '100 BROAD'<br /> >>> s = '100 BROAD ROAD APT. 3'<br /> >>> re.sub(r'\bROAD$', 'RD.', s)  <br /> '100 BROAD ROAD APT. 3'<br /> >>> re.sub(r'\bROAD\b', 'RD.', s) <br /> '100 BROAD RD. APT 3'</p> <p>我真正想要做的是Q当 'ROAD' 出现在字W串的末,q且是作Z个独立的单词Ӟ而不是一些长单词的一部分Q才对他q行匚w。ؓ了在正则表达式中表达q个意思,你利?\bQ它的含义是“单词的边界必dq里”。在 Python 中,׃字符 '\' 在一个字W串中必{义,q会变得非常ȝ。有时候,q类问题被称?#8220;反斜U灾?#8221;Q这也是 Perl 中正则表辑ּ?Python 的正则表辑ּ要相对容易的原因之一。另一斚wQPerl 也؜淆了正则表达式和其他语法Q因此,如果你发C?bugQ很隑ּ清楚I竟是一个语法错误,q是一个正则表辑ּ错误?nbsp; <br />   Z避免反斜U灾难,你可以利用所谓的“原始字符?#8221;Q只要ؓ字符串添加一个前~ r 可以了。这告?PythonQ字W串中的所有字W都不{义;'\t' 是一个制表符Q?r'\t' 是一个真正的反斜U字W?'\'Q紧跟着一个字?'t'。我推荐只要处理正则表达式,׃用原始字W串Q否则,事情会很快变得؜?(q且正则表达式自׃会很快被自己搞ؕ??nbsp; </p> <p> </p> <p>?7.4. 验百位数<br /> >>> import re<br /> >>> pattern = '^M?M?M?(CM|CD|D?C?C?C?)$' <br /> >>> re.search(pattern, 'MCM')            <br /> <SRE_Match object at 01070390><br /> >>> re.search(pattern, 'MD')             <br /> <SRE_Match object at 01073A50><br /> >>> re.search(pattern, 'MMMCCC')         <br /> <SRE_Match object at 010748A8><br /> >>> re.search(pattern, 'MCMC')           <br /> >>> re.search(pattern, '')               <br /> <SRE_Match object at 01071D98></p> <p> </p> <p>?7.5. 老方法:每一个字W都是可选的<br /> >>> import re<br /> >>> pattern = '^M?M?M?$'<br /> >>> re.search(pattern, 'M')    <br /> <_sre.SRE_Match object at 0x008EE090><br /> >>> pattern = '^M?M?M?$'<br /> >>> re.search(pattern, 'MM')   <br /> <_sre.SRE_Match object at 0x008EEB48><br /> >>> pattern = '^M?M?M?$'<br /> >>> re.search(pattern, 'MMM')  <br /> <_sre.SRE_Match object at 0x008EE090><br /> >>> re.search(pattern, 'MMMM') <br /> >>> </p> <p><br /> ?7.6. 一个新的方法:?n ?m<br /> >>> pattern = '^M{0,3}$'       <br /> >>> re.search(pattern, 'M')    <br /> <_sre.SRE_Match object at 0x008EEB48><br /> >>> re.search(pattern, 'MM')   <br /> <_sre.SRE_Match object at 0x008EE090><br /> >>> re.search(pattern, 'MMM')  <br /> <_sre.SRE_Match object at 0x008EEDA8><br /> >>> re.search(pattern, 'MMMM') <br /> >>> </p> <p><br /> 对于个位数的正则表达式有cM的表达方式,我将省略l节Q直接展C结果?/p> <p>>>> pattern = '^M?M?M?(CM|CD|D?C?C?C?)(XC|XL|L?X?X?X?)(IX|IV|V?I?I?I?)$'<br /> 用另一U?{n,m} 语法表达q个正则表达式会如何呢?q个例子展示新的语法?</p> <p>?7.8. ?{n,m} 语法认|马数字 <br /> >>> pattern = '^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$'<br /> >>> re.search(pattern, 'MDLV')             <br /> <_sre.SRE_Match object at 0x008EEB48><br /> >>> re.search(pattern, 'MMDCLXVI')         <br /> <_sre.SRE_Match object at 0x008EEB48></p> <p><br /> ?7.9. 带有内联注释 (Inline Comments) 的正则表辑ּ<br /> >>> pattern = """<br />     ^                   # beginning of string<br />     M{0,3}              # thousands - 0 to 3 M's<br />     (CM|CD|D?C{0,3})    # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's),<br />                         #            or 500-800 (D, followed by 0 to 3 C's)<br />     (XC|XL|L?X{0,3})    # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's),<br />                         #        or 50-80 (L, followed by 0 to 3 X's)<br />     (IX|IV|V?I{0,3})    # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's),<br />                         #        or 5-8 (V, followed by 0 to 3 I's)<br />     $                   # end of string<br />     """<br /> >>> re.search(pattern, 'M', re.VERBOSE)                <br /> <_sre.SRE_Match object at 0x008EEB48><br /> >>> re.search(pattern, 'MCMLXXXIX', re.VERBOSE)        <br /> <_sre.SRE_Match object at 0x008EEB48><br /> >>> re.search(pattern, 'MMMDCCCLXXXVIII', re.VERBOSE)  <br /> <_sre.SRE_Match object at 0x008EEB48><br /> >>> re.search(pattern, 'M')                            <br />   当用松散正则表辑ּӞ最重要的一件事情就是:必须传递一个额外的参数 re.VERBOSEQ该参数是定义在 re 模块中的一个常量,标志着待匹配的正则表达式是一个松散正则表辑ּ。正如你看到的,q个模式中,有很多空?(所有的I格都被忽略)Q和几个注释 (所有的注释也被忽略)。如果忽略所有的I格和注释,它就和前面章节里的正则表辑ּ完全相同Q但是具有更好的可读性?nbsp; <br /> >>> re.search(pattern, 'M')        <br /> q个没有匚w。ؓ什么呢Q因为没?re.VERBOSE 标记Q所?re.search 函数把模式作Z个紧凑正则表辑ּq行匚w。Python 不能自动一个正则表辑ּ是ؓ松散cdq是紧凑cd。Python 默认每一个正则表辑ּ都是紧凑cd的,除非你显式地标明一个正则表辑ּ为松散类型?</p> <p> </p> <p>?7.16. 解析电话L (最l版?<br /> >>> phonePattern = re.compile(r'''<br />                 # don't match beginning of string, number can start anywhere<br />     (\d{3})     # area code is 3 digits (e.g. '800')<br />     \D*         # optional separator is any number of non-digits<br />     (\d{3})     # trunk is 3 digits (e.g. '555')<br />     \D*         # optional separator<br />     (\d{4})     # rest of number is 4 digits (e.g. '1212')<br />     \D*         # optional separator<br />     (\d*)       # extension is optional and can be any number of digits<br />     $           # end of string<br />     ''', re.VERBOSE)<br /> >>> phonePattern.search('work 1-(800) 555.1212 #1234').groups()        <br /> ('800', '555', '1212', '1234')<br /> >>> phonePattern.search('800-555-1212')                                <br /> ('800', '555', '1212', '')</p> <p> </p> <p><br /> 现在Q你应该熟悉下列技巧:</p> <p>^ 匚w字符串的开始?<br /> $ 匚w字符串的l尾?<br /> \b 匚w一个单词的边界?<br /> \d 匚wL数字?<br /> \D 匚wL非数字字W?<br /> x? 匚w一个可选的 x 字符 (换言之,它匹?1 ơ或?0 ?x 字符)?<br /> x* 匚w0ơ或者多?x 字符?<br /> x+ 匚w1ơ或者多?x 字符?<br /> x{n,m} 匚w x 字符Q至?n ơ,臛_ m ơ?<br /> (a|b|c) 要么匚w aQ要么匹?bQ要么匹?c?<br /> (x) 一般情况下表示一个记忆组 (remembered group)。你可以利用 re.search 函数q回对象?groups() 函数获取它的倹{?<br /> <br /> http://www.woodpecker.org.cn/diveintopython/regular_expressions/phone_numbers.html<br /> <br /> <table style="width: 802px; height: 1872px" cellspacing="0" cellpadding="1" width="802" border="1"> <caption> <h5 class="docTableTitle">Regular expression pattern syntax</h5> </caption> <colgroup span="2"> <tbody> <tr> <th class="docTableHeader"> <p class="docText">Element</p> </th> <th class="docTableHeader"> <p class="docText">Meaning</p> </th> </tr> <tr> <td class="docTableCell"><a name="pythonian-CHP-9-ITERM-5256"></a><a name="pythonian-CHP-9-ITERM-5257"></a> <pre>.</pre> </td> <td class="docTableCell"> <p class="docText">Matches any character except <tt>\n</tt> (if <tt>DOTALL</tt>, also matches <tt>\n</tt>)</p> </td> </tr> <tr> <td class="docTableCell"><a name="pythonian-CHP-9-ITERM-5258"></a><a name="pythonian-CHP-9-ITERM-5259"></a> <pre>^</pre> </td> <td class="docTableCell"> <p class="docText">Matches start of string (if <tt>MULTILINE</tt>, also matches after <tt>\n</tt>)</p> </td> </tr> <tr> <td class="docTableCell"><a name="pythonian-CHP-9-ITERM-5260"></a><a name="pythonian-CHP-9-ITERM-5261"></a> <pre>$</pre> </td> <td class="docTableCell"> <p class="docText">Matches end of string (if <tt>MULTILINE</tt>, also matches before <tt>\n</tt>)</p> </td> </tr> <tr> <td class="docTableCell"><a name="pythonian-CHP-9-ITERM-5262"></a><a name="pythonian-CHP-9-ITERM-5263"></a> <pre>*</pre> </td> <td class="docTableCell"> <p class="docText">Matches zero or more cases of the previous regular expression; greedy (match as many as possible)</p> </td> </tr> <tr> <td class="docTableCell"><a name="pythonian-CHP-9-ITERM-5264"></a><a name="pythonian-CHP-9-ITERM-5265"></a> <pre>+</pre> </td> <td class="docTableCell"> <p class="docText">Matches one or more cases of the previous regular expression; greedy (match as many as possible)</p> </td> </tr> <tr> <td class="docTableCell"><a name="pythonian-CHP-9-ITERM-5266"></a><a name="pythonian-CHP-9-ITERM-5267"></a> <pre>?</pre> </td> <td class="docTableCell"> <p class="docText">Matches zero or one case of the previous regular expression; greedy (match one if possible)</p> </td> </tr> <tr> <td class="docTableCell"> <p class="docText"><tt>*?</tt><a name="pythonian-CHP-9-ITERM-5268"></a> <a name="pythonian-CHP-9-ITERM-5269"></a><a name="pythonian-CHP-9-ITERM-5270"></a><a name="pythonian-CHP-9-ITERM-5271"></a>, <tt>+?</tt>, <tt>??</tt></p> </td> <td class="docTableCell"> <p class="docText">Non-greedy versions of <tt>*</tt>, <tt>+</tt>, and <tt>?</tt> (match as few as possible)</p> </td> </tr> <tr> <td class="docTableCell"> <pre>{<tt><em>m</em></tt>,<tt><em>n</em></tt>}</pre> </td> <td class="docTableCell"> <p class="docText">Matches <tt><em>m</em></tt> to <tt><em>n</em></tt> cases of the previous regular expression (greedy)</p> </td> </tr> <tr> <td class="docTableCell"> <pre>{<tt><em>m</em></tt>,<tt><em>n</em></tt>}?</pre> </td> <td class="docTableCell"> <p class="docText">Matches <tt><em>m</em></tt> to <tt><em>n</em></tt> cases of the previous regular expression (non-greedy)</p> </td> </tr> <tr> <td class="docTableCell"><a name="pythonian-CHP-9-ITERM-5272"></a><a name="pythonian-CHP-9-ITERM-5273"></a> <pre>[...]</pre> </td> <td class="docTableCell"> <p class="docText">Matches any one of a set of characters contained within the brackets</p> </td> </tr> <tr> <td class="docTableCell"><a name="pythonian-CHP-9-ITERM-5274"></a><a name="pythonian-CHP-9-ITERM-5275"></a> <pre>|</pre> </td> <td class="docTableCell"> <p class="docText">Matches expression either preceding it or following it</p> </td> </tr> <tr> <td class="docTableCell"><a name="pythonian-CHP-9-ITERM-5276"></a><a name="pythonian-CHP-9-ITERM-5277"></a> <pre>(...)</pre> </td> <td class="docTableCell"> <p class="docText">Matches the regular expression within the parentheses and also indicates a group</p> </td> </tr> <tr> <td class="docTableCell"> <pre>(?iLmsux)</pre> </td> <td class="docTableCell"> <p class="docText">Alternate way to set optional flags; no effect on match</p> </td> </tr> <tr> <td class="docTableCell"> <pre>(?:...)</pre> </td> <td class="docTableCell"> <p class="docText">Like <tt>(...)</tt>, but does not indicate a group</p> </td> </tr> <tr> <td class="docTableCell"> <pre>(?P<<tt><em>id</em></tt>>...)</pre> </td> <td class="docTableCell"> <p class="docText">Like <tt>(...)</tt>, but the group also gets the name <tt><em>id</em></tt></p> </td> </tr> <tr> <td class="docTableCell"> <pre>(?P=<tt><em>id</em></tt>)</pre> </td> <td class="docTableCell"> <p class="docText">Matches whatever was previously matched by group named <tt><em>id</em></tt></p> </td> </tr> <tr> <td class="docTableCell"> <pre>(?#...)</pre> </td> <td class="docTableCell"> <p class="docText">Content of parentheses is just a comment; no effect on match</p> </td> </tr> <tr> <td class="docTableCell"> <pre>(?=...)</pre> </td> <td class="docTableCell"> <p class="docText">Lookahead assertion; matches if regular expression <tt>..</tt>. matches what comes next, but does not consume any part of the string</p> </td> </tr> <tr> <td class="docTableCell"> <pre>(?!...)</pre> </td> <td class="docTableCell"> <p class="docText">Negative lookahead assertion; matches if regular expression <tt>..</tt>. does not match what comes next, and does not consume any part of the string</p> </td> </tr> <tr> <td class="docTableCell"> <pre>(?<=...)</pre> </td> <td class="docTableCell"> <p class="docText">Lookbehind assertion; matches if there is a match for regular expression <tt>..</tt>. ending at the current position (<tt>..</tt>. must match a fixed length)</p> </td> </tr> <tr> <td class="docTableCell"> <pre>(?<!...)</pre> </td> <td class="docTableCell"> <p class="docText">Negative lookbehind assertion; matches if there is no match for regular expression <tt>..</tt>. ending at the current position (<tt>..</tt>. must match a fixed length)</p> </td> </tr> <tr> <td class="docTableCell"> <pre>\<tt><em>number</em></tt></pre> </td> <td class="docTableCell"> <p class="docText">Matches whatever was previously matched by group numbered <tt><em>number</em></tt> (groups are automatically numbered from 1 up to 99)</p> </td> </tr> <tr> <td class="docTableCell"> <pre>\A</pre> </td> <td class="docTableCell"> <p class="docText">Matches an empty string, but only at the start of the whole string</p> </td> </tr> <tr> <td class="docTableCell"> <pre>\b</pre> </td> <td class="docTableCell"> <p class="docText">Matches an empty string, but only at the start or end of a word (a maximal sequence of alphanumeric characters; see also <tt>\w</tt>)</p> </td> </tr> <tr> <td class="docTableCell"> <pre>\B</pre> </td> <td class="docTableCell"> <p class="docText">Matches an empty string, but not at the start or end of a word</p> </td> </tr> <tr> <td class="docTableCell"> <p class="docText">\d</p> </td> <td class="docTableCell"> <p class="docText">Matches one digit, like the set <tt>[0-9]</tt></p> </td> </tr> <tr> <td class="docTableCell"> <pre>\D</pre> </td> <td class="docTableCell"> <p class="docText">Matches one non-digit, like the set <tt>[^0-9]</tt></p> </td> </tr> <tr> <td class="docTableCell"> <pre>\s</pre> </td> <td class="docTableCell"> <p class="docText">Matches a whitespace character, like the set <tt>[</tt> <tt>\t\n\r\f\v]</tt></p> </td> </tr> <tr> <td class="docTableCell"> <pre>\S</pre> </td> <td class="docTableCell"> <p class="docText">Matches a non-white character, like the set <tt>[^</tt> <tt>\t\n\r\f\v]</tt></p> </td> </tr> <tr> <td class="docTableCell"> <pre>\w</pre> </td> <td class="docTableCell"> <p class="docText">Matches one alphanumeric character; unless <tt>LOCALE</tt> or <tt>UNICODE</tt> is set, <tt>\w</tt> is like <tt>[a-zA-Z0-9_]</tt></p> </td> </tr> <tr> <td class="docTableCell"> <pre>\W</pre> </td> <td class="docTableCell"> <p class="docText">Matches one non-alphanumeric character, the reverse of <tt>\w</tt></p> </td> </tr> <tr> <td class="docTableCell"> <pre>\Z</pre> </td> <td class="docTableCell"> <p class="docText">Matches an empty string, but only at the end of the whole string</p> </td> </tr> <tr> <td class="docTableCell"> <pre>\\</pre> </td> <td class="docTableCell"> <p class="docText">Matches one backslash character</p> </td> </tr> </colgroup> </tbody> </table> <a name="pythonian-CHP-9-SECT-7.2"></a></p> <img src ="http://www.aygfsteel.com/fhtdy2004/aggbug/292232.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/fhtdy2004/" target="_blank">Frank_Fang</a> 2009-08-22 23:48 <a href="http://www.aygfsteel.com/fhtdy2004/archive/2009/08/22/292232.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Python学习W记一http://www.aygfsteel.com/fhtdy2004/archive/2009/08/22/292168.htmlFrank_FangFrank_FangFri, 21 Aug 2009 16:02:00 GMThttp://www.aygfsteel.com/fhtdy2004/archive/2009/08/22/292168.htmlhttp://www.aygfsteel.com/fhtdy2004/comments/292168.htmlhttp://www.aygfsteel.com/fhtdy2004/archive/2009/08/22/292168.html#Feedback0http://www.aygfsteel.com/fhtdy2004/comments/commentRss/292168.htmlhttp://www.aygfsteel.com/fhtdy2004/services/trackbacks/292168.html发现很多公司要求掌握一门脚本语aQ一直也x搞这个,看C++QLinux C~程也只是ؓ了对pȝ更加的了解,唉,我的工作定位好像一直都不怎么明确Q是要搞个自己最擅长的了Q以后有旉再搞linuxCQ找工作W一位。。。工作基本定位在 Java+pythonQ大部分公司也不会要求一个h既做Java也做C++。再说这语言也是大同异Q关键还是编E思想


d = {"server":"mpilgrim", "database":"master"}

li = ["a", "b", "mpilgrim", "z", "example"]


Tuple 是不可变?list。一旦创Z一?tupleQ就不能以Q何方式改变它
 t = ("a", "b", "mpilgrim", "z", "example")


q接 list 与分割字W串
>>> li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
>>> s = ";".join(li)
>>> s
'server=mpilgrim;uid=sa;database=master;pwd=secret'
>>> s.split(";")   
['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
>>> s.split(";", 1)
['server=mpilgrim', 'uid=sa;database=master;pwd=secret']

 


使用 type、str、dir 和其它内|函?/p>

4.3.2. str 函数
str 数据强制{换ؓ字符丌Ӏ每U数据类型都可以强制转换为字W串?

?4.6. str 介绍
>>> str(1)         
'1'
>>> horsemen = ['war', 'pestilence', 'famine']
>>> horsemen
['war', 'pestilence', 'famine']
>>> horsemen.append('Powerbuilder')
>>> str(horsemen)  
"['war', 'pestilence', 'famine', 'Powerbuilder']"
>>> str(odbchelper)
"<module 'odbchelper' from 'c:\\docbook\\dip\\py\\odbchelper.py'>"
>>> str(None)      
'None'  对于单的数据cd比如整型Q你可以预料?str 的正常工作,因ؓ几乎每种语言都有一?/p>

整型{化ؓ字符串的函数?nbsp;
  然?str 可以作用于Q何数据类型的M对象。这里它作用于一个零构建的列表?nbsp;
  str q允怽用于模块。注意模块的字符串Ş式表C包含了模块在磁盘上的\径名Q所以你的显C?/p>

l果会有所不同?nbsp;
  str 的一个细但重要的行为是它可以作用于 NoneQNone ?Python ?null 倹{这个调用返回字W?/p>

?'None'。你会使用q一Ҏ改进你的 info 函数Q这一点你很快׃看到?nbsp;


dir 函数q回L对象的属性和Ҏ列表Q包括模块对象、函数对象、字W串对象、列表对象、字

典对?…… 相当多的东西?

?4.7. dir 介绍
>>> li = []
>>> dir(li)          
['append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
>>> d = {}
>>> dir(d)           
['clear', 'copy', 'get', 'has_key', 'items', 'keys', 'setdefault', 'update', 'values']
>>> import odbchelper
>>> dir(odbchelper)  
['__builtins__', '__doc__', '__file__', '__name__', 'buildConnectionString']

 

最后是 callable 函数Q它接收M对象作ؓ参数Q如果参数对象是可调用的Q返?TrueQ否则返?

False。可调用对象包括函数、类ҎQ甚至类自n (下一章将更多的关注类)?

?4.8. callable 介绍
>>> import string
>>> string.punctuation          
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.join                 
<function join at 00C55A7C>
>>> callable(string.punctuation)
False
>>> callable(string.join)       
True


你已l知?Python 函数是对象。你不知道的是,使用 getattr 函数Q可以得C个直到运行时才知

道名U的函数的引用?

?4.10. getattr 介绍
>>> li = ["Larry", "Curly"]
>>> li.pop                      
<built-in method pop of list object at 010DF884>
>>> getattr(li, "pop")          
<built-in method pop of list object at 010DF884>
>>> getattr(li, "append")("Moe")
>>> li
["Larry", "Curly", "Moe"]
>>> getattr({}, "clear")        
<built-in method clear of dictionary object at 00F113D4>
>>> getattr((), "pop")          
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'pop'

 

4.4.1. 用于模块?getattr
getattr 不仅仅适用于内|数据类型,也可作用于模块?

?4.11. apihelper.py 中的 getattr 函数
>>> import odbchelper
>>> odbchelper.buildConnectionString            
<function buildConnectionString at 00D18DD4>
>>> getattr(odbchelper, "buildConnectionString")
<function buildConnectionString at 00D18DD4>
>>> object = odbchelper
>>> method = "buildConnectionString"
>>> getattr(object, method)                     
<function buildConnectionString at 00D18DD4>
>>> type(getattr(object, method))               
<type 'function'>
>>> import types
>>> type(getattr(object, method)) == types.FunctionType
True
>>> callable(getattr(object, method))           
True


使用 getattrQ你能够获得同一函数的同一引用。通常Qgetattr(object, "attribute") {h?

object.attribute。如?object 是一个模块的话,那么 attribute 可能是定义在模块中的M东西Q函?/p>

、类或者全局变量?/p>


是相当于函数的指针
?4.12. 使用getattr 创徏分发?

import statsout

def output(data, format="text"):                             
    output_function = getattr(statsout, "output_%s" % format)
    return output_function(data)                             
  output 函数接收一个必备参?dataQ和一个可选参?format。如果没有指?format 参数Q其~省

值是 text q完成普通文本输出函数的调用?nbsp;
  你可以连?format 参数值和 "output_" 来创Z个函数名UC为参数|然后?statsout 模块中取

得该函数。这U方式允总后很Ҏ地扩展程序以支持其它的输出格式,而且无需修改分发函数?/p>

所要做的仅仅是?statsout 中添加一个函敎ͼ比如 output_pdfQ之后只要将 “pdf” 作ؓ format 的参

数g递给 output 函数卛_?nbsp;
  现在你可以简单地调用输出函数Q就像调用其它函C栗output_function 变量是指?statsout ?/p>

块中相应函数的引用?nbsp;

你是否发现前面示例的一?BugQ即字符串和函数之间的松耦合Q而且没有错误查。如果用户传

入一个格式参敎ͼ但是?statsout 中没有定义相应的格式输出函数Q会发生什么呢Q还好,getattr

会返?NoneQ它会取代一个有效函数ƈ被赋值给 output_functionQ然后下一行调用函数的语句会

p|q抛Z个异常。这U方式不好?

值得庆幸的是Qgetattr 能够使用可选的W三个参敎ͼ一个缺省返回倹{?/p>

 

[mapping-expression for element in source-list if filter-expression]

>>> li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"]
>>> [elem for elem in li if len(elem) > 1]      
['mpilgrim', 'foo']
>>> [elem for elem in li if elem != "b"]        
['a', 'mpilgrim', 'foo', 'c', 'd', 'd']
>>> [elem for elem in li if li.count(elem) == 1]
['a', 'mpilgrim', 'foo', 'c']


使用 and Ӟ在布环境中从左到右演算表达式的倹{??'、[]?)、{}、None 在布环境中为假Q?/p>

其它M东西都ؓ真。还好,几乎是所有东ѝ默认情况下Q布环境中的类实例为真Q但是你?/p>

以在cM定义特定的方法得类实例的演gؓ假?/p>


4.6.1. 使用 and-or 技?
?4.17. and-or 技巧介l?
>>> a = "first"
>>> b = "second"
>>> 1 and a or b
'first'
>>> 0 and a or b
'second'
  q个语法看v来类g C 语言中的 bool ? a : b 表达式。整个表辑ּ从左到右q行演算Q所以先q?/p>

?and 表达式的演算? and 'first' 演算gؓ 'first'Q然?'first' or 'second' 的演gؓ 'first'?nbsp;
  0 and 'first' 演算gؓ FalseQ然?0 or 'second' 演算gؓ 'second'?nbsp;

然而,׃q种 Python 表达式单单只是进行布逻辑q算Qƈ不是语言的特定构成,q是 and-or

技巧和 C 语言中的 bool ? a : b 语法非常重要的不同。如?a 为假Q表辑ּ׃会按你期望的那样

工作了?你能知道我被q个问题折腾q吗Q不止一ơ?)

 

 

 


Python 支持一U有的语法Q它允许你快速定义单行的最函数。这些叫?lambda 的函敎ͼ是从

Lisp 借用来的Q可以用在Q何需要函数的地方?br /> ?4.20. lambda 函数介绍
>>> def f(x):
...     return x*2
...    
>>> f(3)
6
>>> g = lambda x: x*2 
>>> g(3)
6
>>> (lambda x: x*2)(3)
6

ȝ来说Qlambda 函数可以接收L多个参数 (包括可选参? q且q回单个表达式的倹{lambda

函数不能包含命oQ包含的表达式不能超q一个。不要试囑֐ lambda 函数中塞入太多的东西Q如

果你需要更复杂的东西,应该定义一个普通函敎ͼ然后惌它多长就多长?

 


?4.25. 打印列表
>>> li = ['a', 'b', 'c']
>>> print "\n".join(li)
a
b
c  在你处理列表Ӟq确实是一个有用的调试技巧。在 Python 中,你会十分频繁地操作列表?nbsp;

 

?2.2.1 版本之前QPython 没有单独的布数据类型。ؓ了I补这个缺PPython 在布环?(?if

语句) 中几乎接受所有东西,遵@下面的规则:
0 ?false; 其它所有数值皆?true?
IZ ("") ?false; 其它所有字W串皆ؓ true?
I?list ([]) ?false; 其它所?list 皆ؓ true?
I?tuple (()) ?false; 其它所?tuple 皆ؓ true?
I?dictionary ({}) ?false; 其它所?dictionary 皆ؓ true?

 


下面?from module import 的基本语法:


from UserDict import UserDict
它与你所熟知?import module 语法很相|但是有一个重要的区别QUserDict 被直接导入到局?/p>

名字I间MQ所以它可以直接使用Q而不需要加上模块名的限定。你可以导入独立的项或?

from module import * 来导入所有东ѝ?

Python 中的 from module import * ?Java 中的 import module.* QPython 中的 import module ?Java

中的 import module

什么时候你应该使用 from module importQ?

如果你要l常讉K模块的属性和ҎQ且不想一遍又一遍地敲入模块名,使用 from module import

?
如果你想要有选择地导入某些属性和ҎQ而不惌其它的,使用 from module import?
如果模块包含的属性和Ҏ与你的某个模块同名,你必M?import module 来避免名字冲H?/p>

量用 from module import * Q因为判定一个特D的函数或属性是从哪来的有些困难Qƈ且会?/p>

成调试和重构都更困难?/p>


from UserDict import UserDict

class FileInfo(UserDict):
?Python 中,cȝ基类只是单地列在cd后面的小括号里。不像在 Java 中有一个特D的

extends 关键字?nbsp;

Python 支持多重l承。在cd后面的小括号中,你可以列多你惌的类名,以逗号分隔?


class FileInfo(UserDict):
    "store file metadata"
    def __init__(self, filename=None):
        UserDict.__init__(self)       
        self["name"] = filename       
                                         一些伪面向对象语言Q像 Powerbuilder 有一U?#8220;扩展”构造函数和其它事g?/p>

概念Q即父类的方法在子类的方法执行前被自动调用。Python 不是q样Q你必须昄地调用在父类中的合适方法?nbsp;
  我告诉过你,q个cd字典一样工作,那么q里是W一个印象。我们将参数 filename 赋值给对象 name 关键字,作ؓ它的倹{?nbsp; 注意 __init__ Ҏ从不q回一个倹{?nbsp;

Java中是自动调用默认的无参的父类的构造函?/p>

 


?5.9. 定义 UserDict c?

class UserDict:                               
    def __init__(self, dict=None):             
        self.data = {}  ×××××××××××××××××××××××××××××××××××定义cȝ实例变量                         
        if dict is not None: self.update(dict) 
  注意 UserDict 是一个基c,不是从Q何其他类l承而来?nbsp;
  q就是我们在 FileInfo cMq行了覆盖的 __init__ Ҏ。注意这个父cȝ参数列表与子cM同。很

好,每个子类可以拥有自已的参数集Q只要用正的参数调用父类可以了。这里父cL一个定

义初始值的Ҏ (通过?dict 参数中传入一个字?Q这一Ҏ我们?FileInfo 没有用上?br />


××××××××××××××××××××××××××××××××与Java的不?#215;××××××××××××××××××××××××××××××××××
与Java的不同,
1QPython中类的类属性是是在cȝ后面直接定义?br /> 2Q而实例变量是在在__init__Ҏ中直接定义的使用如下方式self.instancevariable=***定义,
3Q然后Python中实例方法都要显C的加上selfQ相当于Java的this)参数Q方法中引用实例?span style="color: red">量时也要通过self来引?/span>

Python 支持数据属?(?Java 叫做 “实例变量”Q在 C++ 中叫 “数据成员”)Q它是由某个特定的类?/p>

例所拥有的数据。在本例中,每个 UserDict 实例拥有一?data 数据属性。要从类外的代码引用

q个属性,需要用实例的名字限定它Qinstance.dataQ限定的Ҏ与你用模块的名字来限定函C

栗要在类的内部引用一个数据属性,我们使用 self 作ؓ限定W。习惯上Q所有的数据属性都?

__init__ Ҏ中初始化为有意义的倹{然而,qƈ不是必须的,因ؓ数据属性,像局部变量一P

当你首次赋给它值的时候突然生?nbsp;
×××××××××××××××××××××××××××××××××与Java的不?#215;×××××××××××××××××××××××××××××××××

Java 支持通过参数列表的重载,也就?一个类可以有同名的多个ҎQ但q些Ҏ或者是参数?/p>

C同,或者是参数的类型不同?br /> Python 两种都不支持QM是没有Q何Ş式的函数重蝲。一?__init__ Ҏ是一?__init__ Ҏ

Q不它有什么样的参数。每个类只能有一?__init__ ҎQƈ且如果一个子cL有一?__init__

ҎQ它L 覆盖父类?__init__ ҎQ甚臛_cd以用不同的参数列表来定义它?

xZ么不支持Ҏ重蝲Q是因ؓPython的参数可以定义默认实参,有缺省?/strong>
×××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××
应该L?__init__ Ҏ中给一个实例的所有数据属性赋予一个初始倹{这样做会节省你在后面

调试的时_不必为捕捉因使用未初始化 (也就是不存在) 的属性而导致的 AttributeError 异常Ҏ?/p>

力?
class MP3FileInfo(FileInfo):
mp3file.__class__  is fileinfo.MP3FileInfo true
mp3file.__class__  is fileinfo.FileInfo         false
isinstance(mp3file,fileinfo.MP3FileInfo)  true
isinstance(mp3file,fileinfo.FileInfo)          true

li=[1,2,3]
li2[1,2,3]
li==li2 true   相当于Java的equals()
li is li2 false 相当于Java?=


5.7. 高专用cL?
除了 __getitem__ ?__setitem__ 之外 Python q有更多的专用函数。某些可以让你模拟出你甚臛_

能不知道的功能?

下面的例子将展示 UserDict 一些其他专用方法?

?5.16. UserDict 中更多的专用Ҏ
    def __repr__(self): return repr(self.data)    
    def __cmp__(self, dict):                      
        if isinstance(dict, UserDict):           
            return cmp(self.data, dict.data)     
        else:                                    
            return cmp(self.data, dict)          
    def __len__(self): return len(self.data)      
    def __delitem__(self, key): del self.data[key]   __repr__ 是一个专用的ҎQ在当调?repr

(instance) 时被调用。repr 函数是一个内|函敎ͼ它返回一个对象的字符串表C。它可以用在M

对象上,不仅仅是cȝ实例。你已经?repr 相当熟悉了,管你不知道它。在交互式窗口中Q当?/p>

只敲入一个变量名Q接着按ENTERQPython 使用 repr 来显C变量的倹{自已用一些数据来创徏一

个字?d Q然后用 print repr(d) 来看一看吧?nbsp;
  __cmp__ 在比较类实例时被调用。通常Q你可以通过使用 == 比较L两个 Python 对象Q不只是

cd例。有一些规则,定义了何时内|数据类型被认ؓ是相{的Q例如,字典在有着全部相同的关

键字和值时是相{的。对于类实例Q你可以定义 __cmp__ ҎQ自已编写比较逻辑Q然后你可以

使用 == 来比较你的类QPython 会替你调用你的 __cmp__ 专用Ҏ?nbsp;
  __len__ 在调?len(instance) 时被调用。len 是一个内|函敎ͼ可以q回一个对象的长度。它可以

用于M被认为理应有长度的对象。字W串?len 是它的字W个敎ͼ字典?len 是它的关键字的个

敎ͼ列表或序列的 len 是元素的个数。对于类实例Q定?__len__ ҎQ接着自已~写长度的计?/p>

Q然后调?len(instance)QPython 替你调用你?__len__ 专用Ҏ?nbsp;
  __delitem__ 在调?del instance[key] 时调?Q你可能记得它作Z字典中删除单个元素的Ҏ?/p>

当你在类实例中?del ӞPython 替你调用 __delitem__ 专用Ҏ?nbsp;

 
?Java 中,通过使用 str1 == str2 可以定两个字符串变量是否指向同一块物理内存位|。这叫做

对象同一性,?Python 中写?str1 is str2。在 Java 中要比较两个字符串|你要使用 str1.equals

(str2)Q在 Python 中,你要使用 str1 == str2。某?Java E序员,他们已经被教授得认ؓQ正是因?/p>

?Java ?== 是通过同一性而不是D行比较,所以世界才会更好。这些h要接?Python 的这

?#8220;严重~失”可能要花些时间?nbsp;


ord("a") 97
ord("A") 65

 

5.8. cd性介l?
你已l知道了数据属性,它们是被一个特定的cd例所拥有的变量。Python 也支持类属性,它们?/p>

q本n所拥有的?

?5.17. cd性介l?/p>

class 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)}


?5.18. 修改cd?Java中的静态变?br /> >>> class counter:
...     count = 0                    
...     def __init__(self):
...         self.__class__.count += 1 #一定得用self.__class__来引用,才是cd量,假如用self.count则定义的是实例变?或者用
            Counter.count +=1
...    
上述代码记录创徏的对象的个数

 

5.9. U有函数
与大多数语言一PPython 也有U有的概念:

U有函数不可以从它们的模块外面被调用
U有cL法不能够从它们的cd面被调用
U有属性不能够从它们的cd面被讉K
与大多数的语a不同Q一?Python 函数Q方法,或属性是U有q是公有Q完全取决于它的名字?

如果一?Python 函数Q类ҎQ或属性的名字以两个下划线开?(但不是结?Q它是私有的Q其?/p>

所有的都是公有的?Python 没有cL法保?的概?(只能用于它们自已的类和子cM)。类Ҏ?/p>

者是U有 (只能在它们自已的cM使用) 或者是公有 (M地方都可使用)?

?MP3FileInfo 中,有两个方法:__parse ?__setitem__。正如我们已l讨的,__setitem__

是一个专有方法;通常Q你不直接调用它Q而是通过在一个类上用字典语法来调用Q但它是公有

的,q且如果有一个真正好的理由,你可以直接调用它 (甚至?fileinfo 模块的外?。然而,

__parse 是私有的Q因为在它的名字前面有两个下划线?

 
?Python 中,所有的专用Ҏ (?__setitem__) 和内|属?(?__doc__) 遵守一个标准的命名习惯

Q开始和l束都有两个下划Uѝ不要对你自已的Ҏ和属性用q种Ҏ命名Q到最后,它只会把?(或其它h) 搞ؕ?

#!/usr/bin/env python
#
coding=utf-8
import os
import sys
from UserDict import UserDict

def stripnulls(data):
    
"strip whitespace and null"
    
return data.replace("\00","").strip()

class FileInfo(UserDict):
    
"store file metadata"
    
def __init__(self,filename=None):
        UserDict.
__init__(self)
        
#will trigger the __setitem__ method,and this method be override in the sub class
        self["name"]=filename

class 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) in self.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 object for files of particular"
    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)[1in fileExtList]
    
def getFileInfoClass(filename,module=sys.modules[FileInfo.__module__]):
        
"get file into class from filename extension"
        subclass 
= "%sFileInfo" % os.path.splitext(filename)[1].upper()[1:]
        
return hasattr(module,subclass) and getattr(module,subclass) or FileInfo
    
return [getFileInfoClass(f)(f) for f in fileList]

if __name__=="__main__":
    
for info in listDirectory("G:\\test",[".mp3"]):
        
print "\n".join(["%s=%s" % (k,v) for (k,v) in info.items()])
        
print
        
        
    


Frank_Fang 2009-08-22 00:02 发表评论
]]>
վ֩ģ壺 פ| ؼ| | | ϲ| | DZɽ| Դ| ɽ| ֹ| ʤ| | | Ž| ԣ| Ǩ| | | ɽ| Ȫ| ɽ| | | | | | ʲ| | | | γ| ʡ| ɳ| ˰| ɳ| | ¡| | | ɽ| |