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).
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.
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.
編碼要求:
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")]}]
)
#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()
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()
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.
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)
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 © 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
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]
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
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://m.tkk7.com/rain1102/archive/2009/06/01/279478.html
關于decorator的詳細介紹在 Python 2.4中的What's new中已經有介紹,大家可以看一下。
基本上調用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只用來處理函數和類方法。
針對于第一種調用形式
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的魔力就是它可以對所修飾的函數進行加工。那么這種加工是在不改變原來函數代碼的情況下進行的。有點象我知道那么一點點的AOP(面向方面編程)的想法。
它適合的場合我能想到的列舉出下:
可能還有許多,你可以自由發揮想象
那么我需要用它嗎?
我想那要看你了。不過,我想在某些情況下,使用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
@audit
def test(a):
print a
test("abc")
運行結果:
('abc',)
abc
#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])
作者:CoderZh(CoderZh的技術博客 - 博客園)
出處:http://coderzh.cnblogs.com/
文章版權歸本人所有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。
同樣地, 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') # 編譯為表達
theString = 'saaaay yes no yaaaass'
print theString.strip('say')
yes no
這樣theString首尾字符在['s', 'a', 'y']中的字符將會被過濾掉. lstrip和rstrip原理以及用法和strip一樣.
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
from __future__ import with_statement
with open('test.txt', 'r') as f:
for line in f:
print line
1 非貪婪flag
注意比較這種情況:
2 如果你要多行匹配,那么加上re.S和re.M標志
re.S:.將會匹配換行符,默認.不會匹配換行符
re.M:^$標志將會匹配每一行,默認^和$只會匹配第一行
但是,如果沒有^標志,
可見,是無需re.M
原文地址:http://www.juyimeng.com/python-multi-line-non-greedy-regular-expression-sample.html
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
用作格式化高亮代碼的
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.