??xml version="1.0" encoding="utf-8" standalone="yes"?>91亚洲国产,国产主播一区二区三区四区,久久97超碰国产精品超碰http://www.aygfsteel.com/zellux/category/21872.htmlq的大二:M 思?{待zh-cnTue, 13 May 2008 00:38:47 GMTTue, 13 May 2008 00:38:47 GMT60VIM Calender中的日记发布到blogger.com的脚?/title><link>http://www.aygfsteel.com/zellux/archive/2008/05/12/200093.html</link><dc:creator>ZelluX</dc:creator><author>ZelluX</author><pubDate>Mon, 12 May 2008 14:04:00 GMT</pubDate><guid>http://www.aygfsteel.com/zellux/archive/2008/05/12/200093.html</guid><wfw:comment>http://www.aygfsteel.com/zellux/comments/200093.html</wfw:comment><comments>http://www.aygfsteel.com/zellux/archive/2008/05/12/200093.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/zellux/comments/commentRss/200093.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/zellux/services/trackbacks/200093.html</trackback:ping><description><![CDATA[VIM Calender是个很好用的写日记的插g(<a >http://www.vim.org/scripts/script.php?script_id=52</a>)<br /><br />水木上的rmrf写了一个同步VIM Calender和Google Calender的脚?<a >http://code.google.com/p/diaryvgc/downloads/list</a>)<br /><br />惛_blogger.com支持通过发送邮件发布日志,于是我也写了个把VIM Calender中的日记发布到blogger.com的脚本?br /><br />q个脚本把发布情况记录在diary/poster.log中,以后每次执行只会发布最新的日志Q同时考虑到当天的日记可能会被修改Qblogger.comg不支持通过email修改日志Q,所以当天的日记不会被发布?br /><br />使用的时候修改开头几行的配置信息卛_<br /><br /><div style="BORDER-RIGHT: #cccccc 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #cccccc 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: #cccccc 1px solid; WIDTH: 98%; WORD-BREAK: break-all; PADDING-TOP: 4px; BORDER-BOTTOM: #cccccc 1px solid; BACKGROUND-COLOR: #eeeeee"><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /><span style="COLOR: #008000">#</span><span style="COLOR: #008000">!/usr/bin/python</span><span style="COLOR: #008000"><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /></span><span style="COLOR: #000000"><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /></span><span style="COLOR: #008000">#</span><span style="COLOR: #008000"> A script for posting diaries created by VIM Calender to blogger.com</span><span style="COLOR: #008000"><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />#</span><span style="COLOR: #008000"> Author: Wang Yuanxuan <zellux@gmail.com></span><span style="COLOR: #008000"><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /></span><span style="COLOR: #000000"><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /></span><span style="COLOR: #0000ff">import</span><span style="COLOR: #000000"> smtplib, os, re, datetime<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /></span><span style="COLOR: #0000ff">from</span><span style="COLOR: #000000"> email.mime.text </span><span style="COLOR: #0000ff">import</span><span style="COLOR: #000000"> MIMEText<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />fromaddr </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> </span><span style="COLOR: #800000"><a href="mailto:xxxxx@fudan.edu.cn'">xxxxx</a></span><span style="COLOR: #800000">@fudan.edu.cn</span><span style="COLOR: #800000">'</span><span style="COLOR: #000000"><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />toaddr </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> </span><span style="COLOR: #800000"><a href="mailto:xxxx.xxxx@blogger.com'">xxxx</a></span><span style="COLOR: #800000">.xxxx@blogger.com</span><span style="COLOR: #800000">'</span><span style="COLOR: #000000"><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />smtpserver </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> </span><span style="COLOR: #800000">'</span><span style="COLOR: #800000">mail.fudan.edu.cn</span><span style="COLOR: #800000">'</span><span style="COLOR: #000000"><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />diarydir </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> </span><span style="COLOR: #800000">'</span><span style="COLOR: #800000">/home/user_name/diary</span><span style="COLOR: #800000">'</span><span style="COLOR: #000000"><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />username </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> </span><span style="COLOR: #800000">'xxxxxx'</span><span style="COLOR: #000000"><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />password </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> </span><span style="COLOR: #800000">'xxxxxx'</span><span style="COLOR: #800000"></span><span style="COLOR: #000000"><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />logpath </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> diarydir </span><span style="COLOR: #000000">+</span><span style="COLOR: #000000"> </span><span style="COLOR: #800000">'</span><span style="COLOR: #800000">/poster.log</span><span style="COLOR: #800000">'</span><span style="COLOR: #000000"><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /></span><span style="COLOR: #0000ff">def</span><span style="COLOR: #000000"> PostMail(title, content):<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />    msg </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> MIMEText(content </span><span style="COLOR: #000000">+</span><span style="COLOR: #000000"> </span><span style="COLOR: #800000">'</span><span style="COLOR: #800000">\r\n#end\r\n</span><span style="COLOR: #800000">'</span><span style="COLOR: #000000">)<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />    msg[</span><span style="COLOR: #800000">'</span><span style="COLOR: #800000">Subject</span><span style="COLOR: #800000">'</span><span style="COLOR: #000000">] </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> title<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />    msg[</span><span style="COLOR: #800000">'</span><span style="COLOR: #800000">From</span><span style="COLOR: #800000">'</span><span style="COLOR: #000000">] </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> fromaddr<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />    msg[</span><span style="COLOR: #800000">'</span><span style="COLOR: #800000">To</span><span style="COLOR: #800000">'</span><span style="COLOR: #000000">] </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> toaddr<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />    server </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> smtplib.SMTP(smtpserver)<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />    server.login(username, password)<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />    </span><span style="COLOR: #008000">#</span><span style="COLOR: #008000"> server.set_debuglevel(1)</span><span style="COLOR: #008000"><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /></span><span style="COLOR: #000000">    server.sendmail(fromaddr, [toaddr], msg.as_string())<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />    server.quit()<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /></span><span style="COLOR: #008000">#</span><span style="COLOR: #008000"> Load log file. Create a new one if not exist.</span><span style="COLOR: #008000"><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /></span><span style="COLOR: #000000">posted </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> []<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /></span><span style="COLOR: #0000ff">if</span><span style="COLOR: #000000"> os.path.isfile(logpath):<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />    temp </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> open(logpath, </span><span style="COLOR: #800000">'</span><span style="COLOR: #800000">r</span><span style="COLOR: #800000">'</span><span style="COLOR: #000000">)<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />    posted </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> [line[:</span><span style="COLOR: #000000">-</span><span style="COLOR: #000000">1</span><span style="COLOR: #000000">] </span><span style="COLOR: #0000ff">for</span><span style="COLOR: #000000"> line </span><span style="COLOR: #0000ff">in</span><span style="COLOR: #000000"> temp.readlines()]<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />    log </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> open(logpath, </span><span style="COLOR: #800000">'</span><span style="COLOR: #800000">a</span><span style="COLOR: #800000">'</span><span style="COLOR: #000000">)<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /></span><span style="COLOR: #0000ff">else</span><span style="COLOR: #000000">:<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />    </span><span style="COLOR: #0000ff">print</span><span style="COLOR: #000000"> </span><span style="COLOR: #800000">"</span><span style="COLOR: #800000">A new poster log has been created at </span><span style="COLOR: #800000">"</span><span style="COLOR: #000000"> </span><span style="COLOR: #000000">+</span><span style="COLOR: #000000"> logpath<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />    log </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> open(logpath, </span><span style="COLOR: #800000">'</span><span style="COLOR: #800000">w</span><span style="COLOR: #800000">'</span><span style="COLOR: #000000">)<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />pattern </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> r</span><span style="COLOR: #800000">'</span><span style="COLOR: #800000">(\d{4})/(\d{1,2})/(\d{1,2}).cal$</span><span style="COLOR: #800000">'</span><span style="COLOR: #000000"><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />scanner </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> re.compile(pattern)<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /></span><span style="COLOR: #0000ff">for</span><span style="COLOR: #000000"> (top, dirname, filenames) </span><span style="COLOR: #0000ff">in</span><span style="COLOR: #000000"> os.walk(diarydir):<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />    </span><span style="COLOR: #0000ff">for</span><span style="COLOR: #000000"> filename </span><span style="COLOR: #0000ff">in</span><span style="COLOR: #000000"> filenames:<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />        fullpath </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> os.path.join(top, filename)<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />        </span><span style="COLOR: #0000ff">if</span><span style="COLOR: #000000"> scanner.search(fullpath):<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />            (year, month, day) </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> scanner.search(fullpath).groups()<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />            filedate </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> datetime.date(int(year), int(month), int(day))<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />            title </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> filedate.isoformat()<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />            </span><span style="COLOR: #0000ff">if</span><span style="COLOR: #000000"> filedate </span><span style="COLOR: #000000">==</span><span style="COLOR: #000000"> datetime.date.today():<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />                </span><span style="COLOR: #0000ff">continue</span><span style="COLOR: #000000"><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />            </span><span style="COLOR: #0000ff">if</span><span style="COLOR: #000000"> fullpath </span><span style="COLOR: #0000ff">not</span><span style="COLOR: #000000"> </span><span style="COLOR: #0000ff">in</span><span style="COLOR: #000000"> posted:<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />                log.write(fullpath </span><span style="COLOR: #000000">+</span><span style="COLOR: #000000"> </span><span style="COLOR: #800000">'</span><span style="COLOR: #800000">\n</span><span style="COLOR: #800000">'</span><span style="COLOR: #000000">)<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />                text </span><span style="COLOR: #000000">=</span><span style="COLOR: #000000"> open(fullpath).read()<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />                PostMail(title, text)<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />                </span><span style="COLOR: #0000ff">print</span><span style="COLOR: #000000"> </span><span style="COLOR: #800000">'</span><span style="COLOR: #800000">The diary </span><span style="COLOR: #800000">'</span><span style="COLOR: #000000"> </span><span style="COLOR: #000000">+</span><span style="COLOR: #000000"> title </span><span style="COLOR: #000000">+</span><span style="COLOR: #000000"> </span><span style="COLOR: #800000">'</span><span style="COLOR: #800000"> has been posted</span><span style="COLOR: #800000">'</span><span style="COLOR: #000000"><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /><br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" />log.close()<br /><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" /></span></div><img src ="http://www.aygfsteel.com/zellux/aggbug/200093.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/zellux/" target="_blank">ZelluX</a> 2008-05-12 22:04 <a href="http://www.aygfsteel.com/zellux/archive/2008/05/12/200093.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>[zz]True closure in Pythonhttp://www.aygfsteel.com/zellux/archive/2008/02/11/179611.htmlZelluXZelluXMon, 11 Feb 2008 08:18:00 GMThttp://www.aygfsteel.com/zellux/archive/2008/02/11/179611.htmlhttp://www.aygfsteel.com/zellux/comments/179611.htmlhttp://www.aygfsteel.com/zellux/archive/2008/02/11/179611.html#Feedback0http://www.aygfsteel.com/zellux/comments/commentRss/179611.htmlhttp://www.aygfsteel.com/zellux/services/trackbacks/179611.html Z么水木上的帖子每行末N是用I格填充的,每次转蝲q要先放到vim里面处理一下。。?br />
by ilovecpp

让Python支持true closure有多难?
只需修改11行代码?/p>

如果你不知道什么是true closureQ这里简单解释一下。Python支持lexicalscopeQ?/p>

>>> def add_n(n):
...     def f(m):
...             return n+m
...     return f
>>> add_2 = add_n(2)
>>> add_2(0)
2
>>> add_2(2)
4

f引用了外层函数add_n的局部变量n。有的是,f引用n的时候,add_n已经l束Qng不存在了。f所以能正常工作Q是因ؓ创徏它的时候就把n作ؓf的上下文(closure)保存了下来,q不随add_nl束而消失?br /> 但是QPython的lexical scope和Scheme/Smalltalk/Rubyq有一点区别:不能在内层函Crebind外层函数的局部变量?br /> >>> def f():
...     def g():
...             n=1
...     n=0
...     g()
...     return n
...
>>> f()
0

q是因ؓPython没有变量声明Q?n=1 自动使n成ؓg的局部变量,也就无法rebind f中的n了。可以说Python的closure是只ȝ。如果你听到有h?Python不支持true closure"Q就是指q个。其实,Python VM能够支持true closure。因为,Python支持内层函数看见外层函数的name rebinding:

>>> def f():
...     def g():
...             yield n
...             yield n
...     x = g()
...     n = 0
...     print x.next()
...     n = 1
...     print x.next()
...
>>> f()
0
1

对于Python的closure实现(flat closure)Q?外层函数rebind name"?内层函数rebind name"其实没有区别。我们知道用global关键字可以rebind module scopename。如果增加一个类似的outer关键字,可以支持rebind outer scope name。真正的限制是Guido不愿意ؓ支持true closure增加关键字?/p>

也可以不增加关键字,而是把global n的语义改?如果outer scope定义了nQrebind outer scope nQ否则rebind module scope n"。简单v见,我没有修改Python的built-in compilerQ而是修改了compiler module(用Python实现的Python compiler)。你只需把下面这个patch打到compiler/symbols.py(Python 2.5.1)可以体验true closure了:

C:\Python\Lib>diff -u compiler/symbols.py.orig compiler/symbols.py
--- compiler/symbols.py.orig    Thu Aug 17 10:28:56 2006
+++ compiler/symbols.py Mon Feb 11 12:03:01 2008
@@ -21,6 +21,7 @@
         self.params = {}
         self.frees = {}
         self.cells = {}
+        self.outers = {}
         self.children = []
         # nested is true if the class could contain free variables,
         # i.e. if it is nested within another function.
@@ -54,8 +55,10 @@
         if self.params.has_key(name):
             raise SyntaxError, "%s in %s is global and parameter" % \
                   (name, self.name)
-        self.globals[name] = 1
-        self.module.add_def(name)
+        if self.nested:
+            self.outers[name] = 1
+        else:
+            self.globals[name] = 1

     def add_param(self, name):
         name = self.mangle(name)
@@ -90,6 +93,8 @@
         """
         if self.globals.has_key(name):
             return SC_GLOBAL
+        if self.outers.has_key(name):
+            return SC_FREE
         if self.cells.has_key(name):
             return SC_CELL
         if self.defs.has_key(name):
@@ -107,6 +112,7 @@
             return ()
         free = {}
         free.update(self.frees)
+        free.update(self.outers)
         for name in self.uses.keys():
             if not (self.defs.has_key(name) or
                     self.globals.has_key(name)):
@@ -134,6 +140,9 @@
         free.
         """
         self.globals[name] = 1
+        if self.outers.has_key(name):
+            self.module.add_def(name)
+            del self.outers[name]
         if self.frees.has_key(name):
             del self.frees[name]
         for child in self.children:

因ؓ我们没有修改built-in compilerQ所以程序要写在字符串里Q用compiler.compile~译Q用exec执行Q?br /> >>> from compiler import compile
>>> s = '''
... def counter():
...     n = 0
...     def inc():
...             global n
...             n += 1
...     def dec():
...             global n
...             n -= 1
...     def get():
...             return n
...     return inc, dec, get
... '''
>>> exec compile(s, '', 'exec')
>>> inc, dec, get = counter()
>>> get()
0
>>> inc()
>>> get()
1
>>> dec()
>>> get()
0

后记

1 搞这个东西的~v是Selfless Python(http://www.voidspace.org.uk/python/weblog/arch_d7_2006_12_16.shtml#e583)。很有趣的bytecode hackQ给一个类中的所有函数补上self参数。既然PythonVM支持true closureQ能不能用类似的手法让Python支持true closure呢?不过很快明白这个在bytecode层面不好弄,q是得修改编译器。不q改hq真是出乎意料地单?/p>

2 Guido早已明确表示不能改变global的语义(因ؓ会媄响现有代码)Q所以这个只是玩玩而已Q不用指望成为现实。当然你可以只发布bytecodeQ大概还能把反编译器搞挂掉?-)
3 我可以理解Guido的决定。除非你之前一直在用SchemeQ否则我觉得像上面counter例子那种一l共享状态的函数q是写成class为好Q至共享状态是什么一目了然。Lexical scope太implicitQ用在开头add_n那种地方挺方便,再复杂就不好了?/p>

又:很抱?q后的故?拖了q么久。写h才发现自p是不懂descriptor?br /> 不过我肯定不会让它烂?/p>

 



ZelluX 2008-02-11 16:18 发表评论
]]>
在Python的for循环中计?/title><link>http://www.aygfsteel.com/zellux/archive/2007/12/25/170396.html</link><dc:creator>ZelluX</dc:creator><author>ZelluX</author><pubDate>Tue, 25 Dec 2007 13:29:00 GMT</pubDate><guid>http://www.aygfsteel.com/zellux/archive/2007/12/25/170396.html</guid><wfw:comment>http://www.aygfsteel.com/zellux/comments/170396.html</wfw:comment><comments>http://www.aygfsteel.com/zellux/archive/2007/12/25/170396.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/zellux/comments/commentRss/170396.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/zellux/services/trackbacks/170396.html</trackback:ping><description><![CDATA[<p>利用enumerate<br /> <br /> for i, obj in enumerate(list):<br />     print i, obj</p> <p>Help on class enumerate in module __builtin__:</p> <p>class enumerate(object)<br />  |  enumerate(iterable) -> iterator for index, value of iterable<br />  |<br />  |  Return an enumerate object.  iterable must be an other object that supports<br />  |  iteration.  The enumerate object yields pairs containing a count (from<br />  |  zero) and a value yielded by the iterable argument.  enumerate is useful<br />  |  for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ...<br />  |<br />  |  Methods defined here:<br />  |<br />  |  __getattribute__(...)<br />  |      x.__getattribute__('name') <==> x.name<br />  |<br />  |  __iter__(...)<br />  |      x.__iter__() <==> iter(x)<br />  |<br />  |  next(...)<br />  |      x.next() -> the next value, or raise StopIteration<br />  |<br />  |  ----------------------------------------------------------------------<br />  |  Data and other attributes defined here:<br />  |<br />  |  __new__ = <built-in method __new__ of type object at 0xb7f35d20><br />  |      T.__new__(S, ...) -> a new object with type S, a subtype of T<br /> </p> <img src ="http://www.aygfsteel.com/zellux/aggbug/170396.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/zellux/" target="_blank">ZelluX</a> 2007-12-25 21:29 <a href="http://www.aygfsteel.com/zellux/archive/2007/12/25/170396.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Python中Dictionarycd的排?/title><link>http://www.aygfsteel.com/zellux/archive/2007/12/04/165260.html</link><dc:creator>ZelluX</dc:creator><author>ZelluX</author><pubDate>Tue, 04 Dec 2007 10:48:00 GMT</pubDate><guid>http://www.aygfsteel.com/zellux/archive/2007/12/04/165260.html</guid><wfw:comment>http://www.aygfsteel.com/zellux/comments/165260.html</wfw:comment><comments>http://www.aygfsteel.com/zellux/archive/2007/12/04/165260.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/zellux/comments/commentRss/165260.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/zellux/services/trackbacks/165260.html</trackback:ping><description><![CDATA[lambda真是王道?br /> <div style="border-right: #cccccc 1px solid; padding-right: 5px; border-top: #cccccc 1px solid; padding-left: 4px; font-size: 13px; padding-bottom: 4px; border-left: #cccccc 1px solid; width: 98%; word-break: break-all; padding-top: 4px; border-bottom: #cccccc 1px solid; background-color: #eeeeee"><img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" alt="" /><span style="color: #008000">#</span><span style="color: #008000">!/usr/bin/env python</span><span style="color: #008000"><br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" alt="" /></span><span style="color: #000000">d</span><span style="color: #000000">=</span><span style="color: #000000">{</span><span style="color: #800000">'</span><span style="color: #800000">a</span><span style="color: #800000">'</span><span style="color: #000000">:</span><span style="color: #000000">1</span><span style="color: #000000">,</span><span style="color: #800000">'</span><span style="color: #800000">b</span><span style="color: #800000">'</span><span style="color: #000000">:</span><span style="color: #000000">5</span><span style="color: #000000">,</span><span style="color: #800000">'</span><span style="color: #800000">c</span><span style="color: #800000">'</span><span style="color: #000000">:</span><span style="color: #000000">4</span><span style="color: #000000">}<br /> <img src="http://www.aygfsteel.com/images/OutliningIndicators/None.gif" align="top" alt="" /></span><span style="color: #0000ff">print</span><span style="color: #000000"> sorted(d.items(), key</span><span style="color: #000000">=</span><span style="color: #0000ff">lambda</span><span style="color: #000000"> (k,v): (v,k))</span></div> <br /> <p>Help on built-in function sorted in module __builtin__:</p> <p>sorted(...)<br />     sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list</p> <p> </p> <img src ="http://www.aygfsteel.com/zellux/aggbug/165260.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/zellux/" target="_blank">ZelluX</a> 2007-12-04 18:48 <a href="http://www.aygfsteel.com/zellux/archive/2007/12/04/165260.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>【{载】Python 中的函数式编E?(1)http://www.aygfsteel.com/zellux/archive/2007/11/23/162699.htmlZelluXZelluXFri, 23 Nov 2007 13:15:00 GMThttp://www.aygfsteel.com/zellux/archive/2007/11/23/162699.htmlhttp://www.aygfsteel.com/zellux/comments/162699.htmlhttp://www.aygfsteel.com/zellux/archive/2007/11/23/162699.html#Feedback0http://www.aygfsteel.com/zellux/comments/commentRss/162699.htmlhttp://www.aygfsteel.com/zellux/services/trackbacks/162699.html阅读全文

ZelluX 2007-11-23 21:15 发表评论
]]>
texttable - module for creating simple ASCII tableshttp://www.aygfsteel.com/zellux/archive/2007/09/10/144122.htmlZelluXZelluXMon, 10 Sep 2007 15:40:00 GMThttp://www.aygfsteel.com/zellux/archive/2007/09/10/144122.htmlhttp://www.aygfsteel.com/zellux/comments/144122.htmlhttp://www.aygfsteel.com/zellux/archive/2007/09/10/144122.html#Feedback0http://www.aygfsteel.com/zellux/comments/commentRss/144122.htmlhttp://www.aygfsteel.com/zellux/services/trackbacks/144122.html http://jefke.free.fr/soft/texttable/
dl:  http://jefke.free.fr/soft/texttable/texttable.py
NAME
    texttable - module for creating simple ASCII tables
FILE
    /usr/lib/python2.3/site-packages/texttable.py
DESCRIPTION
    Example:
        table = Texttable()
        table.header(["Name", "Age"])
        table.set_cols_align(["l", "r"])
        table.add_row(["Xavier\nHuon", 32])
        table.add_row(["Baptiste\nClement", 1])
        table.draw()
    Result:
        +----------+-----+
        |   Name   | Age |
        +==========+=====+
        | Xavier   |  32 |
        | Huon     |     |
        +----------+-----+
        | Baptiste |   1 |
        | Clement  |     |
        +----------+-----+
CLASSES
    exceptions.Exception
        ArraySizeError
    Texttable
    class ArraySizeError(exceptions.Exception)
     |  Exception raised when specified rows don't fit the required size
     |
     |  Methods defined here:
     |
     |  __init__(self, msg)
     |
     |  __str__(self)
     |
     |  ----------------------------------------------------------------------
     |  Methods inherited from exceptions.Exception:
     |
     |  __getitem__(...)
    class Texttable
     |  Methods defined here:
     |
     |  __init__(self, max_width=80)
     |      Constructor
     |      - max_width is an integer, specifying the maximum width of the t
able
     |      - if set to 0, size is unlimited, therefore cells won't be wrapp
ed
     |
     |  add_row(self, array)
     |      Add a row in the rows stack
     |
     |      Cells can contain newlines.
     |
     |  draw(self)
     |      Draw the table
     |
     |  header(self, array)
     |      Specify the header of the table
     |
     |  reset(self)
     |      Reset the instance:
     |      - reset rows and header
     |
     |  set_chars(self, array)
     |      Set the characters used to draw lines between rows and
     |      columns.
     |
     |      The array should contain 4 fields:
     |
     |          [horizontal, vertical, corner, header]
     |
     |      Default is set to:
     |
     |          ['-', '|', '+', '=']
     |
     |  set_cols_align(self, array)
     |      Set the desired columns alignment
     |
     |      The elements of the array should be either "l", "c" or "r"
     |       - "l": column flushed left
     |       - "c": column centered
     |       - "r": column flushed right
     |
     |  set_cols_width(self, array)
     |      Set the desired columns width
     |
     |      The elements of the array should be integers, specifying the
     |      width of each column. For example:
     |
     |           [10, 20, 5]
     |
     |  set_deco(self, deco)
     |      Set the table decoration. 'deco' can be a combinaison of:
     |
     |      Texttable.BORDER: Border around the table
     |      Texttable.HEADER: Horizontal line below the header
     |      Texttable.HLINES: Horizontal lines between rows
     |      Texttable.VLINES: Vertical lines between columns
     |
     |      Example:
     |
     |          Texttable.BORDER | Texttable.HEADER
     |
     |      All of them are enabled by default.
     |
     |  --------------------------------------------------------------------
--
     |  Data and other attributes defined here:
     |
     |  BORDER = 1
     |
     |  HEADER = 4
     |
     |  HLINES = 8
     |
     |  VLINES = 16
DATA
    __all__ = ['Texttable', 'ArraySizeError']
    __author__ = 'Gerome Fournier <jefke(at)free.fr>'
    __credits__ = 'Jeff Kowalczyk:\n    - textwrap improved import\n    - ..
.
    __license__ = 'GPL'
    __revision__ = '$Id: texttable.py,v 1.3 2003/10/05 13:53:39 jef Exp je..
.
    __version__ = '0.3'
VERSION
    0.3
AUTHOR
    Gerome Fournier <jefke(at)free.fr>
CREDITS
    Jeff Kowalczyk:
        - textwrap improved import
        - comment concerning header output


ZelluX 2007-09-10 23:40 发表评论
]]>
燕曦版友信息l计脚本http://www.aygfsteel.com/zellux/archive/2007/09/10/143943.htmlZelluXZelluXMon, 10 Sep 2007 04:27:00 GMThttp://www.aygfsteel.com/zellux/archive/2007/09/10/143943.htmlhttp://www.aygfsteel.com/zellux/comments/143943.htmlhttp://www.aygfsteel.com/zellux/archive/2007/09/10/143943.html#Feedback0http://www.aygfsteel.com/zellux/comments/commentRss/143943.htmlhttp://www.aygfsteel.com/zellux/services/trackbacks/143943.html
import urllib, urllib2, cookielib

class MyConnector:
    
def __init__(self):
        
pass
    
    
def login(self, url):
        cookie 
= cookielib.CookieJar()
        opener 
= urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
        urllib2.install_opener(opener)
        str 
= urllib.urlencode({'id''guest''passwd'''})
        self.sock 
= urllib2.urlopen(url, str)
    
    
def getHTML(self, url):
        self.sock 
= urllib2.urlopen(url)
        
return self.sock.read()

yanxiparser.py
from sgmllib import SGMLParser
import re

class YanxiURLParser(SGMLParser):
    
def reset(self):
        self.result 
= []
        SGMLParser.reset(self)
    
    
def start_a(self, attrs):
        
for (k, v) in attrs:
            
if (k == 'href' and (v.find('bbsanc'>= 0)):
                self.result.append(v)
                
class YanxiHTMLParser:
    
def parse(self, html):
        uid 
= ufrom = ubirth = ufav = ''
        
        html 
= html.replace(r'&nbsp;'' ')
        html 
= html.replace(r'<br />''')
        
        pattern 
= '\xbe\xcd\xca\xc7(.*)\xc0\xb2'
        matchObject 
= re.search(pattern, html)
        uid 
= matchObject.group(1)
        uid 
= uid.strip()
        
        pattern 
= '\xc0\xb4\xd7\xd4(.*)\xa3(\xac|xa1)'
        matchObject 
= re.search(pattern, html)
        ufrom 
= matchObject.group(1)
        ufrom 
= ufrom.strip()
        
        pattern 
= '\xcf\xb2\xbb\xb6(.*)\n'
        matchObject 
= re.search(pattern, html)
        ufav 
= matchObject.group(1)
        ufav 
= ufav.strip()
        
        pattern 
= '\n(.*)\xca\xc7\xce\xd2\xb5\xc4\xc9\xfa\xc8\xd5'
        matchObject 
= re.search(pattern, html)
        ubirth 
= matchObject.group(1)
        ubirth 
= ubirth.strip()
        
return {"id" : uid, "from" : ufrom, "birth" : ubirth, "fav" : ufav}

runner.py
from connector import MyConnector
from yanxiparser import *

rootURL 
= 'http://yanxibbs.cn'
loginURL 
= 'http://yanxibbs.cn/bbslogin.php'
url1 
= 'http://yanxibbs.cn/cgi-bin/bbs/bbs0an?path=%2Fgroups%2FGROUP%5F3%2F06SS%2Fbyxx%2Fbjcy'
url2 
= 'http://yanxibbs.cn/cgi-bin/bbs/bbs0an?path=%2Fgroups%2FGROUP%5F3%2F06SS%2Fbyxx%2Fbjyr'

conn 
= MyConnector()
conn.login(loginURL)

def printInfo(url):
    html 
= conn.getHTML(url)
    urlParser 
= YanxiURLParser()
    htmlParser 
= YanxiHTMLParser()
    urlParser.feed(html)
    
    
for targetURL in urlParser.result:
        html 
= conn.getHTML(rootURL + targetURL)
        info 
= htmlParser.parse(html)
        
print "%(id)s\t%(from)s\t%(birth)s\t%(fav)s" % info
    
printInfo(url1)
printInfo(url2)


ZelluX 2007-09-10 12:27 发表评论
]]>
Python 学习W记 - XML 解析http://www.aygfsteel.com/zellux/archive/2007/08/18/137832.htmlZelluXZelluXSat, 18 Aug 2007 08:33:00 GMThttp://www.aygfsteel.com/zellux/archive/2007/08/18/137832.htmlhttp://www.aygfsteel.com/zellux/comments/137832.htmlhttp://www.aygfsteel.com/zellux/archive/2007/08/18/137832.html#Feedback0http://www.aygfsteel.com/zellux/comments/commentRss/137832.htmlhttp://www.aygfsteel.com/zellux/services/trackbacks/137832.htmlminidom.parse("binary.xml")得到的对象是binary.xml的整dom树,它的W一个结点包含了DOCTYPE的相关信息,对于它的字节点的firstNodeQ貌g般都是空的?br>
2. unicode 相关
string.encode()
sys.getdefaultencoding()
指定.py文g~码的方法:
在每个文件开头加入编码声?br># -*- coding: UTF-8 -*-

3. python目录的lib/site-packages/sitecustomize.py是一个特D的脚本QPython会在启动的时候导入它?br>
4. 搜烦元素Q?br>getElementByTagName()
q回的是一个list

5. 元素属?br>attributes 是一个xml.dom.minidom.NameNodeMap实例Q常用的Ҏ如keys() values()Q同时也有__getitem__ҎQ类gdictionary



ZelluX 2007-08-18 16:33 发表评论
]]>
Python 学习 - File and Directoryhttp://www.aygfsteel.com/zellux/archive/2007/08/15/137066.htmlZelluXZelluXWed, 15 Aug 2007 14:34:00 GMThttp://www.aygfsteel.com/zellux/archive/2007/08/15/137066.htmlhttp://www.aygfsteel.com/zellux/comments/137066.htmlhttp://www.aygfsteel.com/zellux/archive/2007/08/15/137066.html#Feedback0http://www.aygfsteel.com/zellux/comments/commentRss/137066.htmlhttp://www.aygfsteel.com/zellux/services/trackbacks/137066.html1. 几个常用对象Q?br>os.system  执行命o
sys.stdin  sys.stdout
os.path.getsize   获得文g大小
os.path.isdir
os.mkdir
os.listdir

2. walk()函数
很好用的一个函?br>os.path.walk(rootdir, f, arg)
rootdir是要讉K的目录树的根Qf是用户定义的函数Qarg是调用f时用的一个参数?br>对于每一?walk"q程中遇到的目录directoryQ设该目录下的文件列表ؓfilelistQwalk函数会调?br>f(arg, directory, filelist)



ZelluX 2007-08-15 22:34 发表评论
]]>
Python 学习W记 (5)http://www.aygfsteel.com/zellux/archive/2007/08/15/136540.htmlZelluXZelluXTue, 14 Aug 2007 16:07:00 GMThttp://www.aygfsteel.com/zellux/archive/2007/08/15/136540.htmlhttp://www.aygfsteel.com/zellux/comments/136540.htmlhttp://www.aygfsteel.com/zellux/archive/2007/08/15/136540.html#Feedback0http://www.aygfsteel.com/zellux/comments/commentRss/136540.htmlhttp://www.aygfsteel.com/zellux/services/trackbacks/136540.html1. 交换x和y的?nbsp; [x, y] = [y, x]

2. zip()Ҏ把几个lists的第i个元素合成一个tupleQ放在一个新的list中?br>zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

函数式编E相?/strong>

1.  Mapping
map() Ҏ对序列中的每个元素调用某个函敎ͼq回新生成的l果序列?br>有点cM于Ruby的Array.each do | element |
>>> z = map(len, ["abc", "clounds", "rain"])
>>> z
[3, 6, 4]

2. Filtering
qo掉满x件的元素Q类gArray.reject do | element |
>>> x = [5,12,-2,13]
>>> y = filter(lambda z: z > 0, x)
>>> y
[5, 12, 13]

3. List Comprehension
来个复杂的例?br>>>> y
[[0, 2, 22], [1, 5, 12], [2, 3, 33]]
>>> [a for b in y for a in b[1:]]
[2, 22, 5, 12, 3, 33]

4. Reduction
先看CZ
>>> x = reduce(lambda x,y: x+y, range(5))
>>> x
10
执行的顺序是Q首先调用函数处理range(5)前两个|0 + 1 = 1Q然后返回的?作ؓxQl与range(5)的第三个?2Q作为y)?br>最后的l果?+1+2+3+4的?br>q个常用来代替for循环



ZelluX 2007-08-15 00:07 发表评论
]]>
用Python写了个URP查分E序http://www.aygfsteel.com/zellux/archive/2007/08/03/134316.htmlZelluXZelluXFri, 03 Aug 2007 11:50:00 GMThttp://www.aygfsteel.com/zellux/archive/2007/08/03/134316.htmlhttp://www.aygfsteel.com/zellux/comments/134316.htmlhttp://www.aygfsteel.com/zellux/archive/2007/08/03/134316.html#Feedback0http://www.aygfsteel.com/zellux/comments/commentRss/134316.htmlhttp://www.aygfsteel.com/zellux/services/trackbacks/134316.html写得不怎么P像URPParser里处理标{时候直接输ZQ很不规范,不过懒得改了
urpparser.py:
from sgmllib import SGMLParser

class URPParser(SGMLParser):
    
def reset(self):
        self.tdOpen 
= 0
        self.colCount 
= -1
        self.firstRow 
= 1
        self.pieces 
= []
        SGMLParser.reset(self)

    
def start_td(self, attrs):
        
"""
            When encountered with tag td, check whether there's
            an align property in the tag, which will distinguish
            score table from others.
        
"""
            
        
for (k, v) in attrs:
            
if (k == "align"):
                self.tdOpen 
= 1
                
break

    
def end_td(self):
        self.tdOpen 
= 0

    
def handle_data(self, text):
        
if (self.tdOpen > 0):
            
if (len(text.strip()) > 0):
                self.colCount 
+= 1
                
if (self.colCount > 6):
                    self.colCount 
= 0
                    self.firstRow 
= 0
                    
print
                
if (self.firstRow):
                    
return
                
if (self.colCount == 2):
                    
print "\t",
                
else:
                    
print text.strip(),"\t",

gpa.sh:
#!/usr/bin/python
import urllib, cookielib, urllib2

loginURL 
= "http://fdis.fudan.edu.cn:58080/amserver/UI/Login?" +\
           
"goto=http%3A%2F%2Fwww.urp.fudan.edu.cn%3A84%2Feps" +\
           
"tar%2Fapp%2Ffudan%2FframeSub.jsp%3FaffairNO%3D035067"
scoreURL 
= "http://www.urp.fudan.edu.cn:84/epstar/app/fudan/S" +\
           
"coreManger/ScoreViewer/Student/Course.jsp"
logoutURL 
= "http://www.urp.fudan.edu.cn/logout.jsp"

cookie 
= cookielib.CookieJar()
opener 
= urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
urllib2.install_opener(opener)
str 
= urllib.urlencode({'Login.Token1''06301000000''Login.Token2'"yourpassword"})
sock1 
= urllib2.urlopen(loginURL, str)
loginHTML 
= sock1.read()
sock1.close()

sock2 
= urllib2.urlopen(scoreURL)
scoreHTML 
= sock2.read()
sock2.close()

sock3 
= urllib2.urlopen(logoutURL)
sock3.close()

from urpparser import URPParser
parser 
= URPParser()
parser.feed(scoreHTML)
print





ZelluX 2007-08-03 19:50 发表评论
]]>
Python 学习W记 (4)http://www.aygfsteel.com/zellux/archive/2007/08/02/133886.htmlZelluXZelluXWed, 01 Aug 2007 16:30:00 GMThttp://www.aygfsteel.com/zellux/archive/2007/08/02/133886.htmlhttp://www.aygfsteel.com/zellux/comments/133886.htmlhttp://www.aygfsteel.com/zellux/archive/2007/08/02/133886.html#Feedback0http://www.aygfsteel.com/zellux/comments/commentRss/133886.htmlhttp://www.aygfsteel.com/zellux/services/trackbacks/133886.html>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
>>> "%(pwd)s" % params
'secret'
q个东西的用处在于和locals的搭配用,比如样例E序?br>
def handle_comment(self, text):
    self.pieces.append(
"<!--%(text)s-->" % locals()) 

p取了text变量的内宏V?br>不过q样和直接用text变量有什么区别呢Q貌?<!--%s-->" % text也可以啊
水木上问了一下,得到的答案是
发信? Essien5 (宝贝晶~), 信区: Python
? ? Re: 关于locals()的用?br>发信? 水木C֌ (Thu Aug  2 11:16:37 2007), 转信

好处是多个变量是代码很好维护,一一对应
'%s%s.......%s'%(a,b,c,d,....,z)
'%(a)s%(b)s......%(z)s'%locals()
W一U写法前面的%s和后面的变量很难对应hQbug的源?br>后一个就非常直观?br>而且要往中间再随便插变量也方?/span>

2. 自己的类l承了SGMLParser后,需要对Ҏ标记处理Q可以以start_或do_开始命名相兛_数?br>可以q样做的原因在于python的自醒机?introspection)

    def finish_starttag(self, tag, attrs):
        
try:
            method 
= getattr(self, 'start_' + tag)
        
except AttributeError:
            
try:
                method 
= getattr(self, 'do_' + tag)
            
except AttributeError:
                self.unknown_starttag(tag, attrs)
                
return -1
            
else:
                self.handle_starttag(tag, method, attrs)
                
return 0
        
else:
            self.stack.append(tag)
            self.handle_starttag(tag, method, attrs)
            
return 1
E序首先试获得start_tagname的方法,如果p|则l尝试获得do_tagnameQ如果仍然不能找刎ͼ则调用unknown_starttagҎ?br>感觉q和Java的反机制很怼Q例如Javabean中的getter setterҎQ也是通过Ҏ命名的Ş式让其他对象了解自己的?br>
3. import 语句可以写在M地方?br>

ZelluX 2007-08-02 00:30 发表评论
]]>
Python 学习W记 (3)http://www.aygfsteel.com/zellux/archive/2007/07/10/129284.htmlZelluXZelluXTue, 10 Jul 2007 03:00:00 GMThttp://www.aygfsteel.com/zellux/archive/2007/07/10/129284.htmlhttp://www.aygfsteel.com/zellux/comments/129284.htmlhttp://www.aygfsteel.com/zellux/archive/2007/07/10/129284.html#Feedback0http://www.aygfsteel.com/zellux/comments/commentRss/129284.htmlhttp://www.aygfsteel.com/zellux/services/trackbacks/129284.html׃Python的判断语句返回值的Ҏ性,and-or语句可以辑ֈcM三元q算W的效果?br>bool ? a : b
可以写成
bool and a or b

2.
print None 不会输出M信息
需要显CNoneQ要使用print str(None)


ZelluX 2007-07-10 11:00 发表评论
]]>
[zz]Ruby两本书读后感http://www.aygfsteel.com/zellux/archive/2007/06/16/124684.htmlZelluXZelluXSat, 16 Jun 2007 11:54:00 GMThttp://www.aygfsteel.com/zellux/archive/2007/06/16/124684.htmlhttp://www.aygfsteel.com/zellux/comments/124684.htmlhttp://www.aygfsteel.com/zellux/archive/2007/06/16/124684.html#Feedback0http://www.aygfsteel.com/zellux/comments/commentRss/124684.htmlhttp://www.aygfsteel.com/zellux/services/trackbacks/124684.htmlhttp://www.aurora-x.net/blog/oasis/?p=92
by opengl@rygh

现在市面上系l的Q由及q讲Ruby的书凤毛麟角Q这本是分量最重的一本。原书第二版出版到现在也q去两年了,国内刚刚在这个月由博文引q电工发行了译本?br>
800+늚大部_一半是核心库和标准库的参考,另外一半分Z个部分——基、环境、高U。这其中我觉得比较有价值的部分在于“高q一?#8221;有助于让你从一个更高的层次来理解和掌握q门语言Q这一部分也是需要经常参考的部分?/p>

国内目前引q的唯一一本算是讲Ruby的书Q要从这本书开始学习Ruby估计会吓跑不潜在用戗作者是大牛没错Q不q教学则是另一回事了(大家都应有体会,本科上课的时候课讲的最好的老师通常都不是学术最牛的老师Q。缺Ҏ两处很明显:

W一是自向下,它的序是这LQ?/p>

对象和类–>容器、集?#8211;>标准cd–>表达?#8211;>异常和模?#8211;>基本输入输出

一个从上降C又陡然上升的q程。作者自׃说在W一版里q样的效果ƈ不好Q因此在W二版里Ҏ增加了一个介l性章节,_略的先把所有东西列l读者看一遍。虽然vC作用Q但是实际效果我惛_于初学者来说仍然不会太好。C++/Java的书我都读过不少Q也没见哪个是一上来把Class/Objectq些东西甩给读者的QL从基本类型、控制语句过渡。除非你已经对OOq套相当熟悉了,否则上来q个门槛p把一堆新手挡在门外?/p>

接下来的Q谈不上十分晦ӆQ但也不是什么读来轻快的内容Q关键是作者给的例子较,使得象块、P代这些特色难以掌握。再有一点,ruby的语法风格有相当部分q保留有Perl的痕q,而Perl是出了名的以奇怪符可UC世,q些W号在新手眼里不外天书,而高手们则爱不释手?/p>

所以,要能比较利的通过q本书的入门之\Q你得事先具有OO的基Q至一门脚本语a的经验(Perl最佻IQ函数式~程的一些概念(否则当你看到块的一些用法时会很qhQ。然后,可以用RubyW拙的写一些小E序了?/p>

Ruby作ؓ动态语a之一Q它的最大特点自然是“动?#8221;两个字,其著名的“duck typing”是一大体玎ͼ在我看来Q就像是Z接口的调用,但却q不用一个给定的接口M先限Ӟ。这些在高部分里都有专门讲qͼ是应该重点学习的部分?/p>

那么入门I竟用什么书更好Q我推荐《Everyday Scripting with Ruby》这本。和《Programming Ruby》同一个出版社Q今q一月䆾刚出了原版。它是以相当循序渐进的方式带领读者进入Ruby的世界,其是作者精心设计的几个Project是全书亮点(学习一门语a最好的方式q是要动手写E序Q?/p>

最后ȝ如下Q首先看《Everyday》这本书Q跟着书中的指导摆弄过所有的ProjectQƈ完成相应的练习。然后再看《Programmin》一书的Crystallized部分。再之后׃要是当作API参考手册了。花钱去C文版我个得不是很有必要,d四部分中Q前两部分我觉得蛮鸡肋的Q第四部分在电脑上查更方便,只有W三部分有较高的价倹{?/p>

ZelluX 2007-06-16 19:54 发表评论
]]>
Ruby 学习W记 (2)http://www.aygfsteel.com/zellux/archive/2007/06/16/124681.htmlZelluXZelluXSat, 16 Jun 2007 11:30:00 GMThttp://www.aygfsteel.com/zellux/archive/2007/06/16/124681.htmlhttp://www.aygfsteel.com/zellux/comments/124681.htmlhttp://www.aygfsteel.com/zellux/archive/2007/06/16/124681.html#Feedback0http://www.aygfsteel.com/zellux/comments/commentRss/124681.htmlhttp://www.aygfsteel.com/zellux/services/trackbacks/124681.html1. Array#reject Ҏ遍历一个集合的每个元素Qƈ把符合条件的元素删去?br/>例如L数组中的所有素?br/>nums = nums.reject do | num |
prime?(num)
end
puts nums

2. String#chomp Ҏ
str.chomp(separator=$/) => new_str
Returns a new +String+ with the given record separator removed from
the end of _str_ (if present). If +$/+ has not been changed from
the default Ruby record separator, then +chomp+ also removes
carriage return characters (that is it will remove +\n+, +\r+, and
+\r\n+).

"hello".chomp #=> "hello"
"hello\n".chomp #=> "hello"
"hello\r\n".chomp #=> "hello"
"hello\n\r".chomp #=> "hello\n"
"hello\r".chomp #=> "hello"
"hello \n there".chomp #=> "hello \n there"
"hello".chomp("llo") #=> "he"

3. 判断是否在命令行q行脚本
if $0 == __FILE__
check_usage
compare_inventory_files(ARGV[0], ARGV[1])
end
cM于JavacȝmainҎQ在被其他类导入时不会运行其中的代码?/p>

4. Enumerable#any? Ҏ查找一个集合中是否有满x件的元素
irb(main):004:0> deposits = [1, 0, 10000]
irb(main):005:0> deposits.any? do | deposit |
irb(main):006:1* deposit > 9999
irb(main):007:1> end
=> true

5. 关于试
q本?Everyday Scripting with Ruby)的很多程序都是依循测试驱动开发的思想写出来的Q测试单元中的方法通常有两U目的?br/>一U是direct testQ需要测试那个函数就直接调用那个函数Q传递的参数都是直接写出来的?br/>另一U是bootstrapping testQ被试函数的参C是通过生成q些参数的函数生成的Q即一个方法测试了多个对象?br/>Everyone finds their own balance between testing directly and testing indirectly. You will too.

6. Time#strftime Ҏ
t = Time.now
t.strftime("Printed on %m/%d/%Y") #=> "Printed on 04/09/2003"
t.strftime("at %I:%M%p") #=> "at 08:56AM"



ZelluX 2007-06-16 19:30 发表评论
]]>
Ruby 入门W记 (1)http://www.aygfsteel.com/zellux/archive/2007/06/14/124303.htmlZelluXZelluXThu, 14 Jun 2007 06:02:00 GMThttp://www.aygfsteel.com/zellux/archive/2007/06/14/124303.htmlhttp://www.aygfsteel.com/zellux/comments/124303.htmlhttp://www.aygfsteel.com/zellux/archive/2007/06/14/124303.html#Feedback0http://www.aygfsteel.com/zellux/comments/commentRss/124303.htmlhttp://www.aygfsteel.com/zellux/services/trackbacks/124303.html看的是Everyday Scripting with RubyQ风格和In Actionpd差不多,大量的实例?br>现在学Ruby的主要目的也是everyday scriptingQ方便数据处理、生成,文g批处理等QRoR之类的暂时不考虑?br>
1. String.inspect Ҏ
文档中的说法?br>     str.inspect   => string

     Returns a printable version of _str_, with special characters
     escaped.

        str = "hello"
        str[3] = 8
        str.inspect       #=> "hel\010o"

具体情况试试 myString.inspect.inspect....p了解一点了

2. Arrays.each ?Arrays.collect
for_eachҎ

irb(main):007:0> [1, 2, 3].each do | element |
irb(main):008:1*   puts element
irb(main):009:1> end
1
2
3
=> [1, 2, 3]

后者与前者的不同之处在于Q在处理数据的同Ӟ每次处理的返回结果都会保存到一个新的数l中q回?br>irb(main):036:0> newarray = ["aBC", "B"].collect do |e|
irb(main):037:1* e.downcase
irb(main):038:1> end
=> ["abc", "b"]

3. Messages and Methods
It can be hard to remember the difference between messages and methods. A message is a request sent from some sender object. When the receiver object receives the message, it looks to see whether it has a method with the same name. If so, the Ruby code within the method is run, and the results are returned to the sender. The message is the request; the method fulfills it.
呃,q是没有感性认识?br>
4. Delimiting Blocks
块的两种表示方式Q?br>array.each do | element |
    puts element
end
array.each { | element |
    puts element
}
通常使用W一U,但可以用一行写成的情况也可以用第二种Q?br>array.each { | element | puts element }




ZelluX 2007-06-14 14:02 发表评论
]]>
Python 学习W记 (2)http://www.aygfsteel.com/zellux/archive/2007/05/11/116773.htmlZelluXZelluXFri, 11 May 2007 08:22:00 GMThttp://www.aygfsteel.com/zellux/archive/2007/05/11/116773.htmlhttp://www.aygfsteel.com/zellux/comments/116773.htmlhttp://www.aygfsteel.com/zellux/archive/2007/05/11/116773.html#Feedback0http://www.aygfsteel.com/zellux/comments/commentRss/116773.htmlhttp://www.aygfsteel.com/zellux/services/trackbacks/116773.html1. Dictionary cd
1) cM于Java中的Hashtablec,Dictionary定义了键和值的一对一的关pR?br>2) 定义Q{key:value}
d = {"server":"Tomcat", "database":"MySQL"}
3) key对大写敏感?br>4) 可؜用各U数据类型?br>5) 删除元素 del d["server"]
6) 清除所有元?d.clear()

2. List cd
1) 定义Q?br>li = ["a", "b", 1]
2) 下标?开始?br>3) 负数索引从list的尾部向前计数来存取元素Q即
li[-n] == li[len(li) - n]
4) 分片(slice)
>>> li = ['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[1:3]   //从第2个元素到W?个元?br>['b', 'mpilgrim']
>>> li[1:-1]  //从第2个元素到倒数W?个元?br>['b', 'mpilgrim', 'z']
>>> li[:3]
['a', 'b', 'mpilgrim']
>>> li[3:] 
['z', 'example']
>>> li[:]
['a', 'b', 'mpilgrim', 'z', 'example']

5) 增加元素
a) append 末尾q加单个元素
b) insert 单个元素插入某个位|?br>>>> li
['a', 'b', 'mpilgrim', 'z', 'example', 'new']
>>> li.insert(2, "new")           
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']
c) extend 合ƈ另一个List

6) 搜烦
a) index 查找一个值的首次出现q返回烦引|如果没有扑ֈ则引发异常,与Java不同
b) in 操作W测试一个值是否在list?/p>

7) 删除元素
a) remove 删除某个元素Q如不存在则引发异常
b) pop 弹出栈顶元素Q即删除最后一个值ƈq回该?/p>

8) Listq算W?真方便啊 -,=
>>> li = ['a', 'b', 'mpilgrim']
>>> li = li + ['example', 'new']
>>> li
['a', 'b', 'mpilgrim', 'example', 'new']
>>> li += ['two']               
>>> li
['a', 'b', 'mpilgrim', 'example', 'new', 'two']
>>> li = [1, 2] * 3             
>>> li
[1, 2, 1, 2, 1, 2]



ZelluX 2007-05-11 16:22 发表评论
]]>
初学时的W记http://www.aygfsteel.com/zellux/archive/2007/05/02/114991.htmlZelluXZelluXTue, 01 May 2007 17:09:00 GMThttp://www.aygfsteel.com/zellux/archive/2007/05/02/114991.htmlhttp://www.aygfsteel.com/zellux/comments/114991.htmlhttp://www.aygfsteel.com/zellux/archive/2007/05/02/114991.html#Feedback0http://www.aygfsteel.com/zellux/comments/commentRss/114991.htmlhttp://www.aygfsteel.com/zellux/services/trackbacks/114991.html
1. 字符Ԍ
a) 使用三引?’’’?#8221;””)用来指示多行的字W串Q其中可以自q使用单引h双引受?br>b) 自然字符Ԍ在字W串前加上r或RQ表CZ需要{义符Ҏ处理?br>c) Unicode字符Ԍ串前加u?br>d) 和Java一P字符串不可变?br>e) Python没有专门的charcd?br>f) 使用正则表示式时Q徏议用自然表辑ּ处理?br>2. 标识W:必须以字母或下划Uv始,其他部分可以有数字,大小写敏感?br>3. 行:
a) 每个PythonE序都有一些逻辑?logical liens)l成Q后者通常pq物理行(physical lines)l成?br>b) 每个物理行都可以׃条注释结束,不在字符串中?W号表示一条注释?br>c) 在一个交互解释界面中Q必通过输入I来结束多行语句?br>d) ; 可以用于分割一物理行中的不同逻辑行,但Python中很出?;
e) 转义W?\ 也可以用于行末表C在下一行l?br>4. ~进Q?br>a) ~进对于Python中很重要Q错误的~进很有可能会引发错误?br>b) 同一层次的语句必L相同的羃q。每一l这L语句UCؓ一个块?br>5. q算
a) // q回商的整数部分Q即Java中的 \
b) 比较q算W可以被Lq结Q如3<5<7q回True?br>6. 控制?br>a) raw_input(‘Input a number: ‘) 字W串输入到屏q上Qƈ{待用户的输入,q回字符丌Ӏ有点像Basic的input?br>b) if 语句中elif相当于else if。一个简单的if语句Q?br>if True:
    print ‘It is true’
c) Python中没有switch语句Q用if-elif-else代替?br>d) while, for语句中也可以有else:Q注意与while, for寚w
e) for i in range(1, 5)
依次循环i=1, 2, 3, 4
range()q回一个序列的敎ͼ包括1Q不包括5。另外可以再增加一个步长参敎ͼ如range(0, 4, 2)生成0?
f) break语句跛_后,else语句不被执行?br>7. 函数
a) 形参Q函数头中声明的参数Q实参:提供l函数调用的参数?br>b) 函数块ƈ不会修改块外参数的倹{可以用global语句声明为全局变量Q但应尽量避免?br>c) 默认参数|直接在函数头中赋倹{但只有在末参数才可以有默认倹{?br>d) 关键参数?br>

ZelluX 2007-05-02 01:09 发表评论
]]>
վ֩ģ壺 ̳| ƽ| | | ɽ| ˮ| ̨| | | | Ͼ| | ƽ| ݳ| Ϫ| | | ľ| ɽ| ˼| ̫| ɽ| | | ɽ| ɽ| | | Ǽ| | | | ʡ| «| | | | | ʡ| ƽ| ʹ|