亚洲AV永久无码区成人网站,亚洲欧洲日产国产综合网,亚洲综合精品香蕉久久网97http://www.tkk7.com/rain1102/category/37653.html<br/><font color="green" style="font-family: 華文行楷;font-size:16px;">化學結構搜索,化學信息學,生物信息學,實驗室信息學等 。</font><br/><font color="#3C1435">以高科技的生物、化學信息技術實現生命科學領域中專業數據的計算和管理、提高研發能力、增強在科研和成本效率方面的國際競爭力,為生物、化學、醫藥和學術機構提供一流的解決方案和技術咨詢。</font><br/> <br/><font color="green" style="font-family: 華文行楷;font-size:16px;">子曰:危邦不入,亂邦不居。天下有道則見,無道則隱。</font><font color="#3C1435"></font><br/> zh-cnThu, 05 May 2011 01:37:48 GMTThu, 05 May 2011 01:37:48 GMT60Frowns-ChemoInformatics Systemhttp://www.tkk7.com/rain1102/archive/2011/05/04/349531.html周銳周銳Wed, 04 May 2011 13:46:00 GMThttp://www.tkk7.com/rain1102/archive/2011/05/04/349531.htmlhttp://www.tkk7.com/rain1102/comments/349531.htmlhttp://www.tkk7.com/rain1102/archive/2011/05/04/349531.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/349531.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/349531.html Frowns is a chemoinformatics toolkit geared toward rapid development of chemistry related algorithms.  It is written in almost 100% Python with a small portion written in C++.

Frowns is loosely based on the PyDaylight API that Andrew Dalke wrote to wrap the daylight C API.  In some cases programs written using PyDaylight will also work under Frowns with a few minor changes.  A good overview of PyDaylight is available at here.

A good place to look at what Smarts and Smiles are is at the daylight web site located at http://www.daylight.com/

Frowns Features
  • Smiles parser
  • Smarts substructure searching
  • SD file parser with SD field manipulations
  • Depiction for SD files with coordinates
  • Molecule Fingerprint generation
  • Several forms of Ring Detection available
  • Simple aromaticity perception
  • Everything's a graph (i.e. can form canonical strings from incomplete pieces of a molecule)
  • Full source code
  • Really bad depiction of arbitray molecules! (requires AT&T's GraphViz)





周銳 2011-05-04 21:46 發表評論
]]>
cinfony-Open Source cheminformatics toolkits for Pythonhttp://www.tkk7.com/rain1102/archive/2009/11/05/301254.html周銳周銳Thu, 05 Nov 2009 05:07:00 GMThttp://www.tkk7.com/rain1102/archive/2009/11/05/301254.htmlhttp://www.tkk7.com/rain1102/comments/301254.htmlhttp://www.tkk7.com/rain1102/archive/2009/11/05/301254.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/301254.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/301254.htmlBackground

Open Source cheminformatics toolkits such as OpenBabel, the CDK and the RDKit share the same core functionality but support different sets of file formats and forcefields, and calculate different fingerprints and descriptors. Despite their complementary features, using these toolkits in the same program is difficult as they are implemented in different languages (C++ versus Java), have different underlying chemical models and have different application programming interfaces (APIs).

Results

We describe Cinfony, a Python module that presents a common interface to all three of these toolkits, allowing the user to easily combine methods and results from any of the toolkits. In general, the run time of the Cinfony modules is almost as fast as accessing the underlying toolkits directly from C++ or Java, but Cinfony makes it much easier to carry out common tasks in cheminformatics such as reading file formats and calculating descriptors.

Conclusion

By providing a simplified interface and improving interoperability, Cinfony makes it easy to combine complementary features of OpenBabel, the CDK and the RDKit.


Cinfony presents a common API to several cheminformatics toolkits. It uses the Python programming language, and builds on top of OpenBabel, RDKit and the CDK.

 

Documentation



周銳 2009-11-05 13:07 發表評論
]]>
wxPython小試-禮盒編號生成器http://www.tkk7.com/rain1102/archive/2009/08/19/291870.html周銳周銳Wed, 19 Aug 2009 14:30:00 GMThttp://www.tkk7.com/rain1102/archive/2009/08/19/291870.htmlhttp://www.tkk7.com/rain1102/comments/291870.htmlhttp://www.tkk7.com/rain1102/archive/2009/08/19/291870.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/291870.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/291870.html


編碼要求:
1、編碼中不出現“4”、“3”等不吉利數字,缺碼編號;
2、賣品第一個字母“L”表示禮盒裝、“B”表示標準裝。第二個字母是“A”到“Z”中的任意字母,可根據編碼需要任意選擇。四位數字為編號;
3、賣品與贈品區別在于:賣品以“L”或者“B”開頭,贈品以“ZL”或者“ZB”開頭。

例如:
賣品禮盒裝編碼  L-A0001  L-D0001等
賣品標準裝編碼  B-A0001  B-H0888等
贈品禮盒裝編碼  ZL-A0001  ZL-D0001等
贈品標準裝編碼  ZB-A0001  ZB-H0888等
 
其中如果有3個3的號碼也留下來,不用去掉。 本來想用js來實現,但如果那樣只能把生成的結果寫給頁面上了,而且刷新就沒了。

后來考慮了一下,選擇使用wxPython加上py2exe來做一個小的可執行文件,并把生成的編號放入txt文件中。 由于之前沒玩過wxPython,花了1個多小時終于搞定了!代碼如下:

#encoding=utf-8
from __future__ import with_statement
import wx

class ChoiceFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, u'編碼生成器', size=(450, 150))
        icon=wx.EmptyIcon()
        icon.LoadFile("SetupIcon.ico",wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)
        panel = wx.Panel(self, -1)
       
        typeList = [u'賣品禮盒裝',u'賣品標準裝',u'贈品禮盒裝',u'贈品標準裝',]
        wx.StaticText(panel, -1, u"選擇種類:", pos=(10, 20))
        self.type = wx.Choice(panel, -1, (85, 20), choices=typeList)
        self.type.SetSelection(0)
       
        sampleList = [chr(i) for i in range(65,91)]
        wx.StaticText(panel, -1, u"選擇字母:", pos=(210, 20))
        self.choice = wx.Choice(panel, -1, (285, 20), choices=sampleList)
        self.choice.SetStringSelection('A')
       
        wx.StaticText(panel, -1, u"起始數字:", pos=(10, 50))
        self.start = wx.TextCtrl(panel, -1, "", pos=(80, 50))
       
        wx.StaticText(panel, -1, u"結束數字:", pos=(210, 50))
        self.end = wx.TextCtrl(panel, -1, "", pos=(280, 50))
       
        funbtn = wx.Button(panel, -1, u"運行", pos=(280, 90))
        self.Bind(wx.EVT_BUTTON, self.OnFunButton, funbtn)
       
        self.message = wx.StaticText(panel, -1, "", pos=(10, 90))
        self.message.SetForegroundColour("red")
       
    def OnFunButton(self, evt):
        self.message.SetLabel('')
        startNum = self.start.GetValue().strip()
        endNum = self.end.GetValue().strip()
        if not startNum.isdigit():
            self.message.SetLabel(u'*開始數字必須輸入整整數')
            return
        if not endNum.isdigit():
            self.message.SetLabel(u'*結束數字必須輸入整整數')
            return
        snum = int(startNum)
        enum = int(endNum)
        if enum <= snum:
            self.message.SetLabel(u'*結束數字必須大于開始數字')
            return
        if enum >= 10000:
            self.message.SetLabel(u'*結束數字必須小于10000')
            return
        type = self.type.GetSelection()
        choice = self.choice.GetStringSelection()

        if (type == 0):
            type = "L-"
        elif (type == 1):
            type = "B-"
        elif (type == 2):
            type = "ZL-"
        elif (type == 3):
            type = "ZB-"
       
        startCode = self.getCode(snum, type, choice)
        endCode = self.getCode(enum, type, choice)
           
        with open(startCode + "-" + endCode + ".txt", 'w') as f:
            for i in range(snum, enum+1):
                code = self.getCode(i, type, choice)
               
                num4 = code.count('4')
                if num4 > 0:
                    continue
                num3 = code.count('3')
                if num3 >0 and num3 < 3:
                    continue
                f.write(code)
                f.write('\n')
        self.message.SetLabel(u'編號生成成功!!!')
       
    def getCode(self, i, type, choice):
        code = i
        if i < 10:
            code = '000' + str(i)
        elif i < 100:
            code = '00' + str(i)
        elif i < 1000:
            code = '0' + str(i)
        return type + choice+ str(code)
   
if __name__ == '__main__':
    app = wx.PySimpleApp()
    ChoiceFrame().Show()
    app.MainLoop()

 

生成exe的代碼如下:

#encoding=utf-8
from distutils.core import setup
import py2exe

options = {"py2exe":  
            {   "compressed": 1,  
                "bundle_files": 1
            }  
          } 
         
setup(
    options = options,
    zipfile = None,
    windows=[{"script": "GeneratorCode.py", "icon_resources": [(1, "SetupIcon.ico")]}]
)




周銳 2009-08-19 22:30 發表評論
]]>
Beautiful Soup-Python寫的一個HTML/XML的解析器http://www.tkk7.com/rain1102/archive/2009/08/11/290679.html周銳周銳Tue, 11 Aug 2009 05:36:00 GMThttp://www.tkk7.com/rain1102/archive/2009/08/11/290679.htmlhttp://www.tkk7.com/rain1102/comments/290679.htmlhttp://www.tkk7.com/rain1102/archive/2009/08/11/290679.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/290679.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/290679.htmlBeautiful Soup 是用Python寫的一個HTML/XML的解析器,它可以很好的處理不規范標記并生成剖析樹(parse tree)。它提供簡單又常用的導航(navigating),搜索以及修改剖析樹的操作。它可以大大節省你的編程時間。 對于Ruby,使用Rubyful Soup

中文文檔:http://www.crummy.com/software/BeautifulSoup/documentation.zh.html

周銳 2009-08-11 13:36 發表評論
]]>
Python發送Post請求http://www.tkk7.com/rain1102/archive/2009/07/28/288723.html周銳周銳Tue, 28 Jul 2009 06:32:00 GMThttp://www.tkk7.com/rain1102/archive/2009/07/28/288723.htmlhttp://www.tkk7.com/rain1102/comments/288723.htmlhttp://www.tkk7.com/rain1102/archive/2009/07/28/288723.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/288723.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/288723.html由于有很多數據需要逐個翻譯,手工處理比較麻煩,花了十來分鐘寫了個python程序去跑,輕松了很多。具體代碼如下:

#encoding=utf-8
from __future__ import with_statement
import MySQLdb
import urllib
from lister import ListerTR

conn = MySQLdb.connect(host="localhost", user="root", passwd="root", db="coocoo", charset="utf8")
cursor = conn.cursor()
cursor.execute("select id, enname from compound where enname != '' and zhname = '' order by id")
row=cursor.fetchall()
for r in row:
    params = urllib.urlencode({'eng2chi':r[1]})      這里組織參數
    sock = urllib.urlopen("http://202.127.145.134/scdb/translate/translate.asp", params)   發送請求,并把參數傳過去
    html = sock.read()
    sock.close()
    p = ListerTR()   以下為解析返回的數據代碼
    p.feed(html)
    html = p.html
    if u"成功" in html:
        value = p.values[5]
        data = value.strip()
        print r[0], r[1], data    取回翻譯成功的內容更新數據庫里面的值
        cursor.execute("update compound set zhname = %s where id=%s", (data, r[0]))
        conn.commit()
    else:    把翻譯失敗的記錄給文本文件中
        with open('failture.txt', 'a+') as f:
            f.write(str(r[0])+" | "+str(r[1]))
            f.write('\n')
cursor.close()
conn.close()



周銳 2009-07-28 14:32 發表評論
]]>
Python之cx_Oracle操作Oracle數據庫http://www.tkk7.com/rain1102/archive/2009/07/28/288681.html周銳周銳Tue, 28 Jul 2009 01:43:00 GMThttp://www.tkk7.com/rain1102/archive/2009/07/28/288681.htmlhttp://www.tkk7.com/rain1102/comments/288681.htmlhttp://www.tkk7.com/rain1102/archive/2009/07/28/288681.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/288681.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/288681.html#encoding=utf-8
import MySQLdb
import cx_Oracle

orcon = cx_Oracle.connect("username", "password", "172.29.131.25:1521/orcl")
orcursor = orcon.cursor()
orcursor.execute("select columnname from tablename ")
row=orcursor.fetchall()
for r in row:
    for cell in r:
        print cell
orcursor.close()
orcon.close()



周銳 2009-07-28 09:43 發表評論
]]>
Django中獲取所有在線用戶信息http://www.tkk7.com/rain1102/archive/2009/07/08/285893.html周銳周銳Wed, 08 Jul 2009 00:41:00 GMThttp://www.tkk7.com/rain1102/archive/2009/07/08/285893.htmlhttp://www.tkk7.com/rain1102/comments/285893.htmlhttp://www.tkk7.com/rain1102/archive/2009/07/08/285893.html#Feedback1http://www.tkk7.com/rain1102/comments/commentRss/285893.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/285893.htmlhttp://groups.google.it/group/django-users/browse_thread/thread/4ba5652bcbd1f958/958c6e7733a26a9c?hl=it&lnk=gst&q=average+time&rnum=3#958c6e7733a26a9c

So, here is my version, using the cache backend:

from datetime import timedelta, datetime
from django.core.cache import cache
from django.contrib.sites.models import Site

ONLINE_MINUTES = 10
CACHE_KEY = '%s_online_user_ids' % Site.objects.get_current().domain

_last_purged = datetime.now()

def get_online_user_ids():
    user_dict = cache.get(CACHE_KEY)
    return hasattr(user_dict, 'keys') and user_dict.keys() or []

class OnlineUsers(object):
    def process_request(self, request):
        if request.user.is_anonymous():
            return

        user_dict = cache.get(CACHE_KEY)
        if not user_dict:
            # initialization
            user_dict = {}

        now = datetime.now()
        user_dict[request.user.id] = now

        # purge
        global _last_purged
        if _last_purged + timedelta(minutes=ONLINE_MINUTES) < now:
            purge_older_than = now - timedelta(minutes=ONLINE_MINUTES)
            for user_id, last_seen in user_dict.items():
                if last_seen < purge_older_than:
                    del(user_dict[user_id])
            _last_purged = now

        cache.set(CACHE_KEY, user_dict, 60*60*24)

This stores a dictionary in the form: {user_id: last_seen_time, ...}
in the cache and updates the cache once for every request by an
authenticated user.

An alternative would be to store a structure like Jeremy's,
{minute_seen: set(user_id, ...), ...} which I think will result in
nearly the same amount of cache hits on average.

I would like to hear your comments.



周銳 2009-07-08 08:41 發表評論
]]>
Python中使用MySQLdb插入數據中文問題http://www.tkk7.com/rain1102/archive/2009/07/07/285837.html周銳周銳Tue, 07 Jul 2009 08:25:00 GMThttp://www.tkk7.com/rain1102/archive/2009/07/07/285837.htmlhttp://www.tkk7.com/rain1102/comments/285837.htmlhttp://www.tkk7.com/rain1102/archive/2009/07/07/285837.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/285837.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/285837.html 解決辦法:
在創建連接的時候設置一下編碼,如:
conn = MySQLdb.connect(host="localhost", user="root", passwd="root", db="chemical", charset="utf8")

周銳 2009-07-07 16:25 發表評論
]]>
使用Python寫windows service的安裝程序http://www.tkk7.com/rain1102/archive/2009/06/28/284462.html周銳周銳Sun, 28 Jun 2009 04:24:00 GMThttp://www.tkk7.com/rain1102/archive/2009/06/28/284462.htmlhttp://www.tkk7.com/rain1102/comments/284462.htmlhttp://www.tkk7.com/rain1102/archive/2009/06/28/284462.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/284462.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/284462.html首先必須清楚, 在使用python來創建windows服務, 需要使用pywin32類庫, 下載地址:http://sourceforge.net/projects/pywin32/
下面我們創建一個什么也不做的服務,代碼如下:
win32test.py

import win32serviceutil
import win32service
import win32event

class win32test(win32serviceutil.ServiceFramework):
    _svc_name_ = "Python Win32 Service"
    _svc_display_name_ = "Python Win32 Service"
    _svc_description_ = "Just for a demo, do nothing."
    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
       
    def SvcDoRun(self):
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
       
    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
   
if __name__=='__main__':
    win32serviceutil.HandleCommandLine(win32test)

如果你想使用這個服務在啟動或者停用時候做點事, 那么就把你要實現的業務寫給對應的方法里SvcDoRun和SvcStop.

下面我們來使用py2exe來把我們上面的service創建成安裝文件, py2exe下載地址:http://sourceforge.net/projects/py2exe/
setup.py

from distutils.core import setup
import py2exe

class Target:
    def __init__(self, **kw):
        self.__dict__.update(kw)
        # for the versioninfo resources
        self.version = "1.0.0"
        self.company_name = "Founder Software Suzhou Co. Ltd."
        self.copyright = "Copyright &copy; 2009 Founder Software (Suzhou) Co., Ltd. "
        self.name = "Jchem cartridge windows service"


myservice = Target(
    description = 'foo',
    modules = ['win32test'],
    cmdline_style='pywin32',
    icon_resources=[(1, "cartrigde.ico")]
)

options = {"py2exe":  
            {   "compressed": 1,  
                "bundle_files": 1
            }  
          } 
         
setup(
    service=[myservice],
    options = options,
    zipfile = None,
    windows=[{"script": "win32test.py"}],
)


下面就可以使用python setup.py py2exe命令來生成安裝文件了.
生成的安裝文件可以使用一下命令來執行控制服務:
win32test.exe install
win32test.exe start
win32test.exe stop
win32test.exe remove



周銳 2009-06-28 12:24 發表評論
]]>
Python中的marshal模塊和pickle模塊http://www.tkk7.com/rain1102/archive/2009/06/18/283124.html周銳周銳Thu, 18 Jun 2009 14:22:00 GMThttp://www.tkk7.com/rain1102/archive/2009/06/18/283124.htmlhttp://www.tkk7.com/rain1102/comments/283124.htmlhttp://www.tkk7.com/rain1102/archive/2009/06/18/283124.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/283124.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/283124.html 使用 marshal 模塊組合不連續數據:
import marshal
value = (
"this is a string",
[1, 2, 3, 4],
("more tuples", 1.0, 2.3, 4.5),
"this is yet another string"
)
data = marshal.dumps(value)
# intermediate format
print type(data), len(data)
print "-"*50
print repr(data)
print "-"*50
print marshal.loads(data)

輸出結果為:
<type 'str'> 130
--------------------------------------------------
'(\x04\x00\x00\x00s\x10\x00\x00\x00this is a string[\x04\x00\x00\x00i\x01\x00\x00\x00i\x02\x00\x00\x00i\x03\x00\x00\x00i\x04\x00\x00\x00(\x04\x00\x00\x00s\x0b\x00\x00\x00more tuplesg\x00\x00\x00\x00\x00\x00\xf0?gffffff\x02@g\x00\x00\x00\x00\x00\x00\x12@s\x1a\x00\x00\x00this is yet another string'
--------------------------------------------------
('this is a string', [1, 2, 3, 4], ('more tuples', 1.0, 2.2999999999999998, 4.5), 'this is yet another string')

使用 marshal 模塊處理代碼:
import marshal
script = """
print 'hello'
"""
code = compile(script, "<script>", "exec")
data = marshal.dumps(code)
# intermediate format
print type(data), len(data)
print "-"*50
print repr(data)
print "-"*50
exec marshal.loads(data)

輸出結果為:
<type 'str'> 102
--------------------------------------------------
'c\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00@\x00\x00\x00s\t\x00\x00\x00d\x00\x00GHd\x01\x00S(\x02\x00\x00\x00t\x05\x00\x00\x00helloN(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00s\x08\x00\x00\x00<script>s\x08\x00\x00\x00<module>\x02\x00\x00\x00s\x00\x00\x00\x00'
--------------------------------------------------
hello

pickle模塊和marshal用法相同, 它比marshal要慢一些, 但它支持用戶自定義類, 可以處理類實例, 共享的元素, 以及遞歸數據結構等. 不過pickle模塊不能處理code對象. 還有一個 cPickle 模塊, 使用 C 實現了相同的功能, 速度和 marshal 不相上下.

周銳 2009-06-18 22:22 發表評論
]]>
Python中的traceback模塊http://www.tkk7.com/rain1102/archive/2009/06/17/282916.html周銳周銳Wed, 17 Jun 2009 13:37:00 GMThttp://www.tkk7.com/rain1102/archive/2009/06/17/282916.htmlhttp://www.tkk7.com/rain1102/comments/282916.htmlhttp://www.tkk7.com/rain1102/archive/2009/06/17/282916.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/282916.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/282916.html import traceback
try:
    raise SyntaxError, "traceback test"
except:
    traceback.print_exc()

將會在控制臺輸出類似結果:
Traceback (most recent call last):
  File "H:\PythonWorkSpace\Test\src\TracebackTest.py", line 3, in <module>
    raise SyntaxError, "traceback test"
SyntaxError: traceback test

類似在你沒有捕獲異常時候, 解釋器所返回的結果.
你也可以傳入一個文件, 把返回信息寫到文件中去, 如下:
import traceback
import StringIO
try:
    raise SyntaxError, "traceback test"
except:
    fp = StringIO.StringIO()    #創建內存文件對象
    traceback.print_exc(file=fp)
    message = fp.getvalue()
    print message

這樣在控制臺輸出的結果和上面例子一樣
traceback模塊還提供了extract_tb函數來格式化跟蹤返回信息, 得到包含錯誤信息的列表, 如下:

import traceback
import sys

def tracebacktest():
    raise SyntaxError, "traceback test"
try:
    tracebacktest()
except:
    info = sys.exc_info()
    for file, lineno, function, text in traceback.extract_tb(info[2]):
        print file, "line:", lineno, "in", function
        print text
    print "** %s: %s" % info[:2]

控制臺輸出結果如下:
H:\PythonWorkSpace\Test\src\TracebackTest.py line: 7 in <module>
tracebacktest()
H:\PythonWorkSpace\Test\src\TracebackTest.py line: 5 in tracebacktest
raise SyntaxError, "traceback test"
** <type 'exceptions.SyntaxError'>: traceback test






周銳 2009-06-17 21:37 發表評論
]]>
Python中的fileinput模塊和tempfile模塊http://www.tkk7.com/rain1102/archive/2009/06/16/282710.html周銳周銳Tue, 16 Jun 2009 14:37:00 GMThttp://www.tkk7.com/rain1102/archive/2009/06/16/282710.htmlhttp://www.tkk7.com/rain1102/comments/282710.htmlhttp://www.tkk7.com/rain1102/archive/2009/06/16/282710.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/282710.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/282710.html import fileinput
import sys
import glob
import string

for line in fileinput.input("test.txt"):     #處理一個文本文件
    print line

for line in fileinput.input(glob.glob("samples/*.txt")):  #處理多個文本文件
    if fileinput.isfirstline():
       print "------ reading %s ------\n" % fileinput.filename()    #獲取文件名稱
    print str(fileinput.lineno()) + " " + string.upper(line)  #獲取行號和內容, 注意這里的行號是繼前面文件行號來處理的,而不是重新開始計算


tempfile模塊提供給你一個快速創建一個命名唯一的臨時文件

import tempfile
import os

tempf = tempfile.mktemp(dir="D:/")

print "tempfile", "=>", tempf

file = open(tempf, "w+b")
file.write("*" * 1000)
file.seek(0)
print len(file.read()), "bytes"
file.close()

try:
    os.remove(tempf)    #用完以后要注意刪除臨時文件
except OSError:
    pass


當然你還可以通過file = tempfile.TemporaryFile()直接為你創建一個臨時文件,并且打開.

周銳 2009-06-16 22:37 發表評論
]]>
python map/filter/reduce[轉載]http://www.tkk7.com/rain1102/archive/2009/06/14/282218.html周銳周銳Sun, 14 Jun 2009 14:08:00 GMThttp://www.tkk7.com/rain1102/archive/2009/06/14/282218.htmlhttp://www.tkk7.com/rain1102/comments/282218.htmlhttp://www.tkk7.com/rain1102/archive/2009/06/14/282218.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/282218.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/282218.html原文:http://www.liuzhongshu.com/code/python-map-filter-reduce.html
python有幾個內置的函數很有意思:map/filter/reduce,都是對一個集合進行處理,filter很容易理解用于過濾,map用于映射,reduce用于歸并,這幾個詞還是太抽象了,下面的代碼精確的說明了這幾個函數的用途:

def map_imp(function, sequence) :
    if function is None: return list(sequence)
    retvals = []
    for element in sequence:
        if (function(element)):
            retvals.append(element)
            return retvals
def reduce_imp(function, sequence) :
    arg1 = function(sequence[0])
    for arg2 in sequence[1:] :
        arg1 = function(arg1, arg2)
    return arg1
def filter_imp(function, sequence) :
    retvals = []
    for element in sequence:
        if (function is None and element) or function(element) :
            retvals.append(element)
    return retvals

對于這種邏輯性強的東西,用語言來描述是無助的,代碼則要清晰的多。

具體使用方法可以參考另外一篇:http://www.tkk7.com/rain1102/archive/2009/06/01/279478.html



周銳 2009-06-14 22:08 發表評論
]]>
Python中的decorator的使用(java中的annotation)[轉載]http://www.tkk7.com/rain1102/archive/2009/06/13/282093.html周銳周銳Sat, 13 Jun 2009 15:46:00 GMThttp://www.tkk7.com/rain1102/archive/2009/06/13/282093.htmlhttp://www.tkk7.com/rain1102/comments/282093.htmlhttp://www.tkk7.com/rain1102/archive/2009/06/13/282093.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/282093.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/282093.html原文地址:http://www.donews.net/limodou/archive/2004/12/19/207521.aspx

在我以前介紹 Python 2.4 特性的Blog中已經介紹過了decorator了,不過,那時是照貓畫虎,現在再仔細描述一下它的使用。

關于decorator的詳細介紹在 Python 2.4中的What's new中已經有介紹,大家可以看一下。

如何調用decorator

基本上調用decorator有兩種形式

第一種:

@A
def f ():
    ...

這種形式是decorator不帶參數的寫法。最終 Python 會處理為:

f = A(f)

還可以擴展成:

@A
@B
@C
def f ():
    ...

最終 Python 會處理為:

f = A(B(C(f)))

注:文檔上寫的是@A @B @C的形式,但實際上是不行的,要寫成多行。而且執行順序是按函數調用順序來的,先最下面的C,然后是B,然后是A。因此,如果decorator有順序話,一定要注意:先要執行的放在最下面,最后執行的放在最上面。(應該不存在這種倒序的關系)

第二種:

@A(args)
def f ():
    ...

這種形式是decorator帶參數的寫法。那么 Python 會處理為:

def f(): ...
_deco = A(args)
f = _deco(f)

可以看出, Python 會先執行A(args)得到一個decorator函數,然后再按與第一種一樣的方式進行處理。

decorator函數的定義

每一個decorator都對應有相應的函數,它要對后面的函數進行處理,要么返回原來的函數對象,要么返回一個新的函數對象。請注意,decorator只用來處理函數和類方法。

第一種:

針對于第一種調用形式

def A(func):
    #處理func
    #如func.attr='decorated'
    return func
@A
def f(args):pass

上面是對func處理后,仍返回原函數對象。這個decorator函數的參數為要處理的函數。如果要返回一個新的函數,可以為:

def A(func):
    def new_func(args):
        #做一些額外的工作
        return func(args) #調用原函數繼續進行處理
    return new_func
@A
def f(args):pass

要注意 new_func的定義形式要與待處理的函數相同,因此還可以寫得通用一些,如:

def A(func):
    def new_func(*args, **argkw):
        #做一些額外的工作
        return func(*args, **argkw) #調用原函數繼續進行處理
    return new_func
@A
def f(args):pass

可以看出,在A中定義了新的函數,然后A返回這個新的函數。在新函數中,先處理一些事情,比如對參數進行檢查,或做一些其它的工作,然后再調原始的函數進行處理。這種模式可以看成,在調用函數前,通過使用decorator技術,可以在調用函數之前進行了一些處理。如果你想在調用函數之后進行一些處理,或者再進一步,在調用函數之后,根據函數的返回值進行一些處理可以寫成這樣:

def A(func):
    def new_func(*args, **argkw):
        result = func(*args, **argkw) #調用原函數繼續進行處理
        if result:
            #做一些額外的工作
            return new_result
        else:
            return result
    return new_func
@A
def f(args):pass

第二種:

針對第二種調用形式

在文檔上說,如果你的decorator在調用時使用了參數,那么你的decorator函數只會使用這些參數進行調用,因此你需要返回一個新的decorator函數,這樣就與第一種形式一致了。

def A(arg):
    def _A(func):
        def new_func(args):
            #做一些額外的工作
            return func(args)
        return new_func
    return _A
@A(arg)
def f(args):pass

可以看出A(arg)返回了一個新的 decorator _A。

decorator的應用場景

不過我也一直在想,到底decorator的魔力是什么?適合在哪些場合呢?是否我需要使用它呢?

decorator的魔力就是它可以對所修飾的函數進行加工。那么這種加工是在不改變原來函數代碼的情況下進行的。有點象我知道那么一點點的AOP(面向方面編程)的想法。

它適合的場合我能想到的列舉出下:

  1. 象文檔中所說,最初是為了使調用staticmethod和classmethod這樣的方法更方便
  2. 在某些函數執行前做一些工作,如web開發中,許多函數在調用前需要先檢查一下用戶是否已經登錄,然后才能調用
  3. 在某此函數執行后做一些工作,如調用完畢后,根據返回狀態寫日志
  4. 做參數檢查

可能還有許多,你可以自由發揮想象

那么我需要用它嗎?

我想那要看你了。不過,我想在某些情況下,使用decorator可以增加程序的靈活性,減少耦合度。比如前面所說的用戶登錄檢查。的確可以寫一個通用的登錄檢查函數,然后在每個函數中進行調用。但這樣會造成函數不夠靈活,而且增加了與其它函數之間的結合程度。如果用戶登錄檢查功能有所修改,比如返回值的判斷發生了變化,有可能每個用到它的函數都要修改。而使用decorator不會造成這一問題。同時使用decorator的語法也使得代碼簡單,清晰(一但你熟悉它的語法的話)。當然你不使用它是可以的。不過,這種函數之間相互結合的方式,更符合搭積木的要求,它可以把函數功能進一步分解,使得功能足夠簡單和單一。然后再通過decorator的機制靈活的把相關的函數串成一個串,這么一想,還真是不錯。比如下面:

@A
@B
def account(args):pass

假設這是一個記帳處理函數,account只管記帳。但一個真正的記帳還有一些判斷和處理,比如:B檢查帳戶狀態,A記日志。這樣的效果其實是先檢查B、通過在A中的處理可以先執行account,然后再進行記日志的處理。象搭積木一樣很方便,改起來也容易。甚至可以把account也寫成decorator,而下面執行的函數是一個空函數。然后再通過配置文件等方法,將decorator的組合保存起來,就基本實現功能的組裝化。是不是非常理想。

Python 帶給人的創造力真是無窮啊!



Trackback: http://tb.donews.net/TrackBack.aspx?PostId=207521



周銳 2009-06-13 23:46 發表評論
]]>
python中自定義annotationhttp://www.tkk7.com/rain1102/archive/2009/06/13/282091.html周銳周銳Sat, 13 Jun 2009 15:17:00 GMThttp://www.tkk7.com/rain1102/archive/2009/06/13/282091.htmlhttp://www.tkk7.com/rain1102/comments/282091.htmlhttp://www.tkk7.com/rain1102/archive/2009/06/13/282091.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/282091.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/282091.htmldef audit(fn):
    def new(*args):
        print args        #這里可以修改參數, 做一些處理, 如果不像讓方法繼續執行下去,  可以直接return None
        return fn(*args)
    return new

@audit
def test(a):
    print a

test("abc")

運行結果:
('abc',)
abc



周銳 2009-06-13 23:17 發表評論
]]>
使用PIL截圖http://www.tkk7.com/rain1102/archive/2009/06/13/281963.html周銳周銳Sat, 13 Jun 2009 01:19:00 GMThttp://www.tkk7.com/rain1102/archive/2009/06/13/281963.htmlhttp://www.tkk7.com/rain1102/comments/281963.htmlhttp://www.tkk7.com/rain1102/archive/2009/06/13/281963.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/281963.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/281963.html import os
im = ImageGrab.grab() 
im.save("c:/screenprint.png")  # 或者直接使用im.show()去顯示截屏
os.execvp( "mspaint",('mspaint','c:\screenprint.png'))  #使用paint打開截圖



周銳 2009-06-13 09:19 發表評論
]]>
python程序刪除svn文件http://www.tkk7.com/rain1102/archive/2009/06/12/281931.html周銳周銳Fri, 12 Jun 2009 15:19:00 GMThttp://www.tkk7.com/rain1102/archive/2009/06/12/281931.htmlhttp://www.tkk7.com/rain1102/comments/281931.htmlhttp://www.tkk7.com/rain1102/archive/2009/06/12/281931.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/281931.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/281931.html

#coding=utf-8
import os
import shutil
import sys
import stat

def deleteSubFile(svnpath):
    names = os.listdir(svnpath)
    for name in names:
       
        fp = os.path.join( svnpath, name)
        if (os.path.isfile(fp)):
            os.chmod( fp, stat.S_IWRITE)
            os.remove(fp)
        else:
            deleteSubFile(fp)
            

def deleteSVN(parentPath = None, dir = None):
    if (dir != None and dir == '.svn'):
        deleteSubFile(os.path.join( parentPath, dir))
        shutil.rmtree(os.path.join( parentPath, dir), True, False)
        print 'deleted ', os.path.join( parentPath, dir)
    else:
        if (dir != None):
            filePath = os.path.join( parentPath, dir)
        else:
            filePath = parentPath
        names = os.listdir(filePath)
        for name in names:
            fp = os.path.join( filePath, name)
            if (os.path.isdir(fp)):
                deleteSVN(filePath, name)


if len(sys.argv) < 2:
    print 'Usage: python % <file path>' % os.path.basename(sys.argv[0])
    sys.exit(-1)

if os.path.isfile(sys.argv[1]):
    print '請選擇文件夾, 而不是文件'
else:
    deleteSVN(parentPath = sys.argv[1])



bat文件代碼如下:
python D:/DeleteSVN.py "%1"
@pause

這樣把包含svn文件的文件夾直接拉到bat文件中, 就會刪除掉里面所有svn文件


周銳 2009-06-12 23:19 發表評論
]]>
Python中修改只讀文件為可讀文件http://www.tkk7.com/rain1102/archive/2009/06/12/281928.html周銳周銳Fri, 12 Jun 2009 15:00:00 GMThttp://www.tkk7.com/rain1102/archive/2009/06/12/281928.htmlhttp://www.tkk7.com/rain1102/comments/281928.htmlhttp://www.tkk7.com/rain1102/archive/2009/06/12/281928.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/281928.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/281928.htmlimport os
import stat
os.chmod( filename, stat.S_IWRITE )


周銳 2009-06-12 23:00 發表評論
]]>
Python中獲取隨機字符串http://www.tkk7.com/rain1102/archive/2009/06/08/280764.html周銳周銳Mon, 08 Jun 2009 14:28:00 GMThttp://www.tkk7.com/rain1102/archive/2009/06/08/280764.htmlhttp://www.tkk7.com/rain1102/comments/280764.htmlhttp://www.tkk7.com/rain1102/archive/2009/06/08/280764.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/280764.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/280764.html list = 'abcdefghijklmnopqrstuvwxyz$&()#@'
import string, random
password = string.join(random.sample(list, 6), sep='')
user.set_password(password)


注意需要使用random和string模塊, 前者是用來獲取隨機字符, 后者是把list轉化為字符串形式.


周銳 2009-06-08 22:28 發表評論
]]>
深入理解yield [轉載]http://www.tkk7.com/rain1102/archive/2009/06/06/280355.html周銳周銳Sat, 06 Jun 2009 11:53:00 GMThttp://www.tkk7.com/rain1102/archive/2009/06/06/280355.htmlhttp://www.tkk7.com/rain1102/comments/280355.htmlhttp://www.tkk7.com/rain1102/archive/2009/06/06/280355.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/280355.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/280355.html yield的英文單詞意思是生產,剛接觸Python的時候感到非常困惑,一直沒弄明白yield的用法。只是粗略的知道yield可以用來為一個函數返回值塞數據,比如下面的例子:
def addlist(alist):
    
for i in alist:
        
yield i + 1
取出alist的每一項,然后把i + 1塞進去。然后通過調用取出每一項:
alist = [1234]
for x in addlist(alist):
    
print x,
這的確是yield應用的一個例子,但是,看過limodou的文章《2.5版yield之學習心得》,并自己反復體驗后,對yield有了一個全新的理解。

1. 包含yield的函數

假如你看到某個函數包含了yield,這意味著這個函數已經是一個Generator,它的執行會和其他普通的函數有很多不同。比如下面的簡單的函數:
def h():
    
print 'To be brave'
    
yield 5

h()
可以看到,調用h()之后,print 語句并沒有執行!這就是yield,那么,如何讓print 語句執行呢?這就是后面要討論的問題,通過后面的討論和學習,就會明白yield的工作原理了。

2. yield是一個表達式

Python2.5以前,yield是一個語句,但現在2.5中,yield是一個表達式(Expression),比如:
= yield 5
表達式(yield 5)的返回值將賦值給m,所以,認為 m = 5 是錯誤的。那么如何獲取(yield 5)的返回值呢?需要用到后面要介紹的send(msg)方法。

3. 透過next()語句看原理

現在,我們來揭曉yield的工作原理。我們知道,我們上面的h()被調用后并沒有執行,因為它有yield表達式,因此,我們通過next()語句讓它執行。next()語句將恢復Generator執行,并直到下一個yield表達式處。比如:
def h():
    
print 'Wen Chuan'
    
yield 5
    
print 'Fighting!'

= h()
c.next()
c.next()調用后,h()開始執行,直到遇到yield 5,因此輸出結果:
Wen Chuan
當我們再次調用c.next()時,會繼續執行,直到找到下一個yield表達式。由于后面沒有yield了,因此會拋出異常:
Wen Chuan
Fighting!
Traceback (most recent call last):
  File 
"/home/evergreen/Codes/yidld.py", line 11in <module>
    c.next()
StopIteration

4. send(msg) 與 next()

了解了next()如何讓包含yield的函數執行后,我們再來看另外一個非常重要的函數send(msg)。其實next()和send()在一定意義上作用是相似的,區別是send()可以傳遞yield表達式的值進去,而next()不能傳遞特定的值,只能傳遞None進去。因此,我們可以看做
c.next() 和 c.send(None) 作用是一樣的。
來看這個例子:
def h():
    
print 'Wen Chuan',
    m 
= yield 5  # Fighting!
    print m
    d 
= yield 12
    
print 'We are together!'

= h()
c.next()  
#相當于c.send(None)
c.send('Fighting!')  #(yield 5)表達式被賦予了'Fighting!'
輸出的結果為:
Wen Chuan Fighting!
需要提醒的是,第一次調用時,請使用next()語句或是send(None),不能使用send發送一個非None的值,否則會出錯的,因為沒有yield語句來接收這個值。

5. send(msg) 與 next()的返回值

send(msg) 和 next()是有返回值的,它們的返回值很特殊,返回的是下一個yield表達式的參數。比如yield 5,則返回 5 。到這里,是不是明白了一些什么東西?本文第一個例子中,通過for i in alist 遍歷 Generator,其實是每次都調用了alist.Next(),而每次alist.Next()的返回值正是yield的參數,即我們開始認為被壓進去的東東。我們再延續上面的例子:
def h():
    
print 'Wen Chuan',
    m 
= yield 5  # Fighting!
    print m
    d 
= yield 12
    
print 'We are together!'

= h()
= c.next()  #m 獲取了yield 5 的參數值 5
= c.send('Fighting!')  #d 獲取了yield 12 的參數值12
print 'We will never forget the date', m, '.', d
輸出結果:
Wen Chuan Fighting!
We will never forget the date 5 . 12

6. throw() 與 close()中斷 Generator

中斷Generator是一個非常靈活的技巧,可以通過throw拋出一個GeneratorExit異常來終止Generator。Close()方法作用是一樣的,其實內部它是調用了throw(GeneratorExit)的。我們看:
def close(self):
    
try:
        self.throw(GeneratorExit)
    
except (GeneratorExit, StopIteration):
        
pass
    
else:
        
raise RuntimeError("generator ignored GeneratorExit")
# Other exceptions are not caught
因此,當我們調用了close()方法后,再調用next()或是send(msg)的話會拋出一個異常:
Traceback (most recent call last):
  File 
"/home/evergreen/Codes/yidld.py", line 14in <module>
    d 
= c.send('Fighting!')  #d 獲取了yield 12 的參數值12
StopIteration

注:以上觀點屬于本人的個人理解,如有偏差請批評指正。謝謝!

作者:CoderZhCoderZh的技術博客 - 博客園
出處:http://coderzh.cnblogs.com/
文章版權歸本人所有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。



周銳 2009-06-06 19:53 發表評論
]]>
python中eval, exec, execfile,和compile [轉載]http://www.tkk7.com/rain1102/archive/2009/06/04/280085.html周銳周銳Thu, 04 Jun 2009 14:07:00 GMThttp://www.tkk7.com/rain1102/archive/2009/06/04/280085.htmlhttp://www.tkk7.com/rain1102/comments/280085.htmlhttp://www.tkk7.com/rain1102/archive/2009/06/04/280085.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/280085.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/280085.htmleval(str [,globals [,locals ]])函數將字符串str當成有效Python表達式來求值,并返回計算結果。

同樣地, exec語句將字符串str當成有效Python代碼來執行.提供給exec的代碼的名稱空間和exec語句的名稱空間相同.

最后,execfile(filename [,globals [,locals ]])函數可以用來執行一個文件,看下面的例子:

>>> eval('3+4')
7
>>> exec 'a=100'
>>> a
100
>>> execfile(r'c:\test.py')
hello,world!
>>>
默認的,eval(),exec,execfile()所運行的代碼都位于當前的名字空間中. eval(), exec,和 execfile()函數也可以接受一個或兩個可選字典參數作為代碼執行的全局名字空間和局部名字空間. 例如:

1 globals = {'x': 7,
2            'y': 10,
3            'birds': ['Parrot', 'Swallow', 'Albatross']
4           }
5 locals = { }
6
7 # 將上邊的字典作為全局和局部名稱空間
8 a = eval("3*x + 4*y", globals, locals)
9 exec "for b in birds: print b" in globals, locals   # 注意這里的語法
10 execfile("foo.py", globals, locals)

如果你省略了一個或者兩個名稱空間參數,那么當前的全局和局部名稱空間就被使用.如果一個函數體內嵌嵌套函數或lambda匿名函數時,同時又在函數主體中使用exec或execfile()函數時, 由于牽到嵌套作用域,會引發一個SyntaxError異常.(此段原文:If you omit one or both namespaces, the current values of the global and local namespaces are used. Also,due to issues related to nested scopes, the use of exec or execfile() inside a function body may result in a SyntaxError exception if that function also contains nested function definitions or uses the lambda operator.)

在Python2.4中俺未發現可以引起異常
注意例子中exec語句的用法和eval(), execfile()是不一樣的. exec是一個語句(就象print或while), 而eval()和execfile()則是內建函數.
exec(str) 這種形式也被接受,但是它沒有返回值。
當一個字符串被exec,eval(),或execfile()執行時,解釋器會先將它們編譯為字節代碼,然后再執行.這個過程比較耗時,所以如果需要對某段代碼執行很多次時,最好還是對該代碼先進行預編譯,這樣就不需要每次都編譯一遍代碼,可以有效提高程序的執行效率。
compile(str ,filename ,kind )函數將一個字符串編譯為字節代碼, str是將要被編譯的字符串, filename是定義該字符串變量的文件,kind參數指定了代碼被編譯的類型-- 'single'指單個語句, 'exec'指多個語句, 'eval'指一個表達式. cmpile()函數返回一個代碼對象,該對象當然也可以被傳遞給eval()函數和exec語句來執行,例如:

1 str = "for i in range(0,10): print i"
2 c = compile(str,'','exec')      # 編譯為字節代碼對象
3 exec c                          # 執行
4
5 str2 = "3*x + 4*y"
6 c2 = compile(str2, '', 'eval')  # 編譯為表達



周銳 2009-06-04 22:07 發表評論
]]>
Python中的 strip, lstrip和rstrip使用方法http://www.tkk7.com/rain1102/archive/2009/06/04/280067.html周銳周銳Thu, 04 Jun 2009 12:22:00 GMThttp://www.tkk7.com/rain1102/archive/2009/06/04/280067.htmlhttp://www.tkk7.com/rain1102/comments/280067.htmlhttp://www.tkk7.com/rain1102/archive/2009/06/04/280067.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/280067.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/280067.html

theString = 'saaaay yes no yaaaass'
print theString.strip('say')

 yes no

這樣theString首尾字符在['s', 'a', 'y']中的字符將會被過濾掉. lstrip和rstrip原理以及用法和strip一樣.



周銳 2009-06-04 20:22 發表評論
]]>
ljust, rjust, center, zfill和%http://www.tkk7.com/rain1102/archive/2009/06/03/279897.html周銳周銳Wed, 03 Jun 2009 13:08:00 GMThttp://www.tkk7.com/rain1102/archive/2009/06/03/279897.htmlhttp://www.tkk7.com/rain1102/comments/279897.htmlhttp://www.tkk7.com/rain1102/archive/2009/06/03/279897.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/279897.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/279897.html >>> for x in range(1, 11):
... print repr(x).rjust(2), repr(x*x).rjust(3),
... # Note trailing comma on previous line
... print repr(x*x*x).rjust(4)
...
 1    1       1
 2    4       8
 3    9     27
 4   16     64
 5   25   125
 6   36   216
 7   49   343
 8   64   512
 9   81   729
10 100 1000

當然你也可以使用%來處理輸出結果
>>> for x in range(1,11):
... print ’%2d %3d %4d’ % (x, x*x, x*x*x)
...
 1    1       1
 2    4       8
 3    9     27
 4   16     64
 5   25   125
 6   36   216
 7   49   343
 8   64   512
 9   81   729
10 100 1000
zfill()則用于向數值的字符串表達式左側填充0, 該函數可以正確理解正負號:
>>> '12'.zfill(5)
'00012’
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'

如果有超過一個的字符串需要格式化為一體, 就需要將它們傳入一個元組作為右值, 如:
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print '%-10s ==> %10d'  %  (name, phone)
...
Jack       ==>       4098
Dcab      ==>       7678
Sjoerd    ==>       4127

當然還有一個更好用的就是格式化時候使用變量名:
>>>table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>>print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
該技巧在與內置函數vars()組合使用非常有用, 該函數返回一個包含所有局部變量的字典.

周銳 2009-06-03 21:08 發表評論
]]>
Python中的集合操作http://www.tkk7.com/rain1102/archive/2009/06/02/279691.html周銳周銳Tue, 02 Jun 2009 13:24:00 GMThttp://www.tkk7.com/rain1102/archive/2009/06/02/279691.htmlhttp://www.tkk7.com/rain1102/comments/279691.htmlhttp://www.tkk7.com/rain1102/archive/2009/06/02/279691.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/279691.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/279691.html
>>> basket = [’apple’, ’orange’, ’apple’, ’pear’, ’orange’, ’banana’]
>>> fruit = set(basket) # create a set without duplicates
>>> fruit
set([’orange’, ’pear’, ’apple’, ’banana’])
>>> ’orange’ in fruit # fast membership testing
True
>>> ’crabgrass’ in fruit
False
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set(’abracadabra’)
>>> b = set(’alacazam’)
>>> a # unique letters in a
set([’a’, ’r’, ’b’, ’c’, ’d’])
>>> a - b # letters in a but not in b
set([’r’, ’d’, ’b’])
>>> a | b # letters in either a or b
set([’a’, ’c’, ’r’, ’d’, ’b’, ’m’, ’z’, ’l’])
>>> a & b # letters in both a and b
set([’a’, ’c’])
>>> a ^ b # letters in a or b but not both
set([’r’, ’d’, ’b’, ’m’, ’z’, ’l’])

周銳 2009-06-02 21:24 發表評論
]]>
Python鏈表類型對象所含有的方法http://www.tkk7.com/rain1102/archive/2009/06/01/279478.html周銳周銳Mon, 01 Jun 2009 14:38:00 GMThttp://www.tkk7.com/rain1102/archive/2009/06/01/279478.htmlhttp://www.tkk7.com/rain1102/comments/279478.htmlhttp://www.tkk7.com/rain1102/archive/2009/06/01/279478.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/279478.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/279478.html 把一個元素添加到鏈表的結尾, 相當于a[len(a):] = [x] 或者a[len(a):] = x
extend(L)
通過添加指定鏈表的所有元素來擴充鏈表, 相當于a[len(a):] = L
insert(i, x)
在指定位置插入一個元素.
remove(x)
刪除鏈表中值為x的第一個元素, 如果沒有這樣的元素, 則會返回一個錯誤.
pop([i])
從鏈表的指定位置刪除元素,并將其返回. 如果沒有指定索引, a.pop()返回最后一個元素.
index(x)
返回鏈表中第一個值為x的元素的索引. 如果沒有匹配的元素就會返回一個錯誤.
count(x)
返回x在鏈表中出現的次數
sort()
對鏈表中的元素進行排序.
reverse()
鏈表順序翻轉

另外鏈表對象還有幾個內置函數非常有用:
filter(function, sequence)
返回一個序列, 包含了給定序列中所有調用function(item)后返回值為true的元素.
map(function, sequence)
為每個元素一次調用function(item)并將返回值組成一個鏈表返回.
可以傳入多個序列, 但函數的參數個數必須和序列個數一致, 執行時會一次用各個序列上對應的元素來調用函數(如果某些序列比其他短,則用None代替).
reduce(function, sequence)
返回一個單值, 首先以序列的前兩個元素調用函數, 再以返回的值和第三個參數調用, 一次執行下去.
可以傳入第三個參數作為初始值.
sum(sequence)
計算序列總和

def f(x):
    return x % 2 != 0 and x % 3 != 0
print filter(f, range(2, 25))

[5, 7, 11, 13, 17, 19, 23]

def cube(x):
    return x * x * x
print map(cube, range(1, 11))

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

def add(x, y):
    return x + y
print map(add, range(1, 5), range(3, 7))

[4, 6, 8, 10]

print reduce(add, range(1, 11))

55

print sum(range(1, 11))

55



周銳 2009-06-01 22:38 發表評論
]]>
Python中啟動執行文件http://www.tkk7.com/rain1102/archive/2009/06/01/279460.html周銳周銳Mon, 01 Jun 2009 12:55:00 GMThttp://www.tkk7.com/rain1102/archive/2009/06/01/279460.htmlhttp://www.tkk7.com/rain1102/comments/279460.htmlhttp://www.tkk7.com/rain1102/archive/2009/06/01/279460.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/279460.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/279460.htmlimport os
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
    execfile(filename)


周銳 2009-06-01 20:55 發表評論
]]>
python中__future__ 模塊以及with語句http://www.tkk7.com/rain1102/archive/2009/05/27/278185.html周銳周銳Wed, 27 May 2009 05:33:00 GMThttp://www.tkk7.com/rain1102/archive/2009/05/27/278185.htmlhttp://www.tkk7.com/rain1102/comments/278185.htmlhttp://www.tkk7.com/rain1102/archive/2009/05/27/278185.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/278185.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/278185.html

from __future__ import with_statement

with open('test.txt', 'r') as f:
    for line in f:
        print line

with方式語句可以替換以前try..catch語句, 如果使用try..catch語句則為:
try:
    f = open('test.txt', 'r')
    for line in f:
        print line
finally:
    f.close()

而with代碼塊如果內部出現任何錯誤, 都將會自動調用close方法

如果上面的with代碼塊沒有使用from __future__ import with_statement, 代碼將會報錯, 提示你這個功能在2.6中實現.
Warning: 'with' will become a reserved keyword in Python 2.6

周銳 2009-05-27 13:33 發表評論
]]>
python非貪婪、多行匹配正則表達式例子[轉載]http://www.tkk7.com/rain1102/archive/2009/05/26/278107.html周銳周銳Tue, 26 May 2009 14:42:00 GMThttp://www.tkk7.com/rain1102/archive/2009/05/26/278107.htmlhttp://www.tkk7.com/rain1102/comments/278107.htmlhttp://www.tkk7.com/rain1102/archive/2009/05/26/278107.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/278107.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/278107.html一些regular的tips:

1 非貪婪flag

>>> re.findall(r"a(\d+?)", "a23b")
        
['2']
>>>
re.findall(r"a(\d+)", "a23b")
        
['23']

注意比較這種情況:

>>> re.findall(r"a(\d+)b", "a23b")
        
['23']
>>>
re.findall(r"a(\d+?)b", "a23b")
        
['23']

2 如果你要多行匹配,那么加上re.S和re.M標志
re.S:.將會匹配換行符,默認.不會匹配換行符

>>> re.findall(r"a(\d+)b.+a(\d+)b", "a23b\na34b")
        
[]
>>>
re.findall(r"a(\d+)b.+a(\d+)b", "a23b\na34b", re.S)
        
[('23', '34')]
>>>

re.M:^$標志將會匹配每一行,默認^和$只會匹配第一行

>>> re.findall(r"^a(\d+)b", "a23b\na34b")
        
['23']
>>>
re.findall(r"^a(\d+)b", "a23b\na34b", re.M)
        
['23', '34']

但是,如果沒有^標志,

>>> re.findall(r"a(\d+)b", "a23b\na23b")
        
['23', '23']

可見,是無需re.M

原文地址:http://www.juyimeng.com/python-multi-line-non-greedy-regular-expression-sample.html



周銳 2009-05-26 22:42 發表評論
]]>
使用Python正則表達式從文章中取出所有圖片路徑http://www.tkk7.com/rain1102/archive/2009/05/26/278090.html周銳周銳Tue, 26 May 2009 13:15:00 GMThttp://www.tkk7.com/rain1102/archive/2009/05/26/278090.htmlhttp://www.tkk7.com/rain1102/comments/278090.htmlhttp://www.tkk7.com/rain1102/archive/2009/05/26/278090.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/278090.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/278090.htmlimport re

name = '''you test this is for mae <img src="/upload/images/123455.jpg"/>, test for you just liook <img src="/upload/images/1test455.jpg"/>'''
result = re.findall('<img src="(.*?)"/>', name, re.S)
print result



結果為:
['/upload/images/123455.jpg', '/upload/images/1test455.jpg']

當然如何你的img標簽和src屬性之間還有其他屬性, 則你也可以直接取src, 如:
result = re.findall('src="(.*?)"/>', name, re.S)


周銳 2009-05-26 21:15 發表評論
]]>
pygments, markdown和textilehttp://www.tkk7.com/rain1102/archive/2009/04/29/268235.html周銳周銳Wed, 29 Apr 2009 13:18:00 GMThttp://www.tkk7.com/rain1102/archive/2009/04/29/268235.htmlhttp://www.tkk7.com/rain1102/comments/268235.htmlhttp://www.tkk7.com/rain1102/archive/2009/04/29/268235.html#Feedback0http://www.tkk7.com/rain1102/comments/commentRss/268235.htmlhttp://www.tkk7.com/rain1102/services/trackbacks/268235.html這三個東西在很多python web程序需要的模塊,都是對文本進行格式化。
pygments

用作格式化高亮代碼的


python-markdown


提供類似wiki格式的格式化功能(mark text轉html)
http://www.freewisdom.org/projects/python-markdown/

markdown的幫助文檔:
http://www.unix-center.net/moodle/help.php?file=markdown.html
http://daringfireball.net/projects/markdown/basics

python-textile


Textile is an XHTML generator that uses a simple markup, similar to the one you can find on most wikis.

This is a Python module that implements a parser and generator that supports the Textile markup syntax.

 



周銳 2009-04-29 21:18 發表評論
]]>
主站蜘蛛池模板: 国产亚洲sss在线播放| 亚洲午夜成人精品电影在线观看 | 日本特黄特色免费大片| 亚洲人成在线免费观看| 九九精品免费视频| 亚洲人成免费网站| 嫩草影院免费观看| 国产成人综合亚洲绿色| 在线免费观看韩国a视频| 国产精品日本亚洲777| 亚洲黄片毛片在线观看| 中文在线观看免费网站| **俄罗斯毛片免费| 亚洲手机中文字幕| 中文字幕av无码无卡免费| 亚洲国产精品无码观看久久| 99免费精品视频| 亚洲国产一区在线| 性短视频在线观看免费不卡流畅| 亚洲久悠悠色悠在线播放| 精品国产免费观看久久久| 一级做a爰黑人又硬又粗免费看51社区国产精品视 | 亚洲精品国产精品乱码在线观看| 国产激情免费视频在线观看| 亚洲黄色在线网站| 情侣视频精品免费的国产| 一本一道dvd在线观看免费视频| 亚洲午夜国产精品无码| 蜜臀98精品国产免费观看| 亚洲成av人片在www鸭子| 国产亚洲日韩在线三区| 成年人视频免费在线观看| 亚洲av无码专区在线电影天堂| 国产亚洲色婷婷久久99精品91| 亚洲欧洲免费视频| 国产精品亚洲а∨天堂2021| 国产亚洲AV无码AV男人的天堂| 青娱乐免费在线视频| 一级特黄a免费大片| 亚洲日本国产乱码va在线观看| 免费a级毛片无码av|