robot
最新文章(10)
Mqskit 和其它相關工具
CPython 的 GC 二、三事
寫 Mecurial Extension 是件快樂的事!
Mozilla 台灣辨公室徵人啟事
關於 Apple 的兩項專利
core dump 之前的 frame
怎麼發出 beep 聲?
先承認你要找的是奴才吧!
程式碼要清的多乾淨?
FreeBSD 的 Thread-Local Storage 實作
首頁
新編
最新留言
Entries RSS
重要關鍵字(10)
coding (122)
Python (93)
FreeBSD (71)
WEB (61)
URL (48)
hardware (46)
javascript (36)
Linux (34)
blog (30)
C++ (16)
所有關鍵字
新增 URL
Python data tourist
by thinker
2 Columns
關鍵字:
Python
coding
自從使用過 $XSLT$ 之後,發覺 XLST 做到 representation 和 data 分離的潛能驚人。另一方面,卻又發覺的 $XSLT$ 以 $XML$ 定義的缺點。我們有必要在使用另一種語言來定義轉換的過程嗎?為何不用我們最熟悉的語言?近幾年,我最常用的語言是 $Python$,理所當然的,我在 $Python$ 試作這個概念;以 $Python$ 定義 $XSLT$ 的 processing model。 這個 module 定名為 tourist ,我也不知是否合適。主要的目的是讓 travel 由 $Python$ object 所組成的 tree。透過定義適當的 path,讓 tourist 在 travel時,遇到指定的 path 時,自動執行對應的 action。 tourist 的功能很簡單,幾乎是課堂上的作業。但是透過限定其介面,當我們需要將資料轉成 XHTML 或 $XML$ 等形式時,就不需重新思索該如何處理。這也是 programmer 的重要思考工具,模組化後,簡化思考單元,改進工作效率。 稍待之後,再補上實際$範例$! {{{ class tnode(object): def __init__(self, name, obj, parent): super(tnode, self).__init__() self.name = name self.obj = obj self.parent = parent try: self.name_path = parent.name_path + (name,) except AttributeError: self.anme_path = (name,) pass pass class tourist(object): primitive_types = (int, long, float, complex, str) def __init__(self): super(tourist,self).__init__() pass def walk(self, name, obj): waiting_objs = [tnode(name, obj, None)] idx = 0 while len(waiting_objs) > idx: visit = waiting_objs[idx] idx = idx + 1 act = self.find_action(visit) if act: act(visit) else: self.append_children_on(visit, waiting_objs) pass pass pass def find_action(self, visit): pass def append_children_on(self, visit, waiting_objs): obj = visit.obj if isinstance(obj, self.primitive_types): return if isinstance(obj, dict): for key in obj: new_node = tnode(key, obj[key], visit) waiting_objs.append(new_node) pass return for name in obj.__dict__: child = getattr(obj, name) if not isinstance(child, (list, tuple)): children = (child,) else: children = child pass for child in children: new_node = tnode(name, child, visit) waiting_objs.append(new_node) pass pass pass pass class act_desc(object): def __init__(self, path, action): super(act_desc, self).__init__() self.path = path self.action = action pass pass class name_tourist(tourist): def __init__(self, actions): super(name_tourist, self).__init__() self.actions = actions pass def find_action(self, visit): for desc in self.actions: path = desc.path action = desc.action traceback = visit rpath = list(path) rpath.reverse() for name in rpath: if name != '*' and name != traceback.name: break traceback = traceback.parent pass else: return action pass pass pass if __name__ == '__main__': def pname(node): print node.name, node.obj pass class foo(object): pass o = foo() o.ll = {} o.ll['aa'] = foo() o.ll['aa'].bb = 1 o.bb = foo() o.bb.aa = foo() actions = (act_desc(('aa', 'bb'), pname),) nt = name_tourist(actions) nt.walk('root', o) pass }}}
最後更新時間: 2006-10-20 14:41:24 CST |
引用
查詢:
COMMENTS: