robot
最新文章(10)
快樂的小成就
Pythonkey 計劃
Mqskit 和其它相關工具
CPython 的 GC 二、三事
寫 Mecurial Extension 是件快樂的事!
Mozilla 台灣辨公室徵人啟事
關於 Apple 的兩項專利
core dump 之前的 frame
怎麼發出 beep 聲?
先承認你要找的是奴才吧!
首頁
新編
最新留言
Entries RSS
重要關鍵字(10)
coding (122)
Python (91)
FreeBSD (71)
WEB (61)
URL (48)
hardware (46)
javascript (36)
Linux (34)
blog (30)
C++ (16)
所有關鍵字
新增 URL
再戰 Python 中文
by thinker
2 Columns
關鍵字:
Python
coding
不久之前,寫了一般 linkname:[$Python$ 與中文] http://heaven.branda.to/~thinker/GinGin_CGI.py/show_id_doc/190 ,提出一個 $Python$ 中文的解決方案。但使用起來總是不順手,尤其是使用其它 library 時,別人的 code 不一定按照我們的規矩走。想了想,於是想出一個 work around 的方式。 目前 $Python$ 中文的主要問題是 str() 並不理會 locale 的設定,而 print 則是可以正常運作。然而,str() 卻是隨處可見,一一更改根本就不實際。不如斧底抽薪,直接把 str() 換成我們的 code ,為 str() 加上一層 wrap ,去呼叫 charset 的codecs 。 換掉 str() 是很容易,但是另一個問題出現了。如果有人呼叫 isinstance(xx, str) 或者 isinstance(xx, (.., str, ..)) ,而 str 又被我們換掉,那又該怎麼辨?那就再 wrap isinstance() 吧! 怎麼做?請在程式的入口 (main module) 執行下面的程式碼。這些程式碼最好是在 import 任何 module 之前執行。 {{{ import locale, codecs orig_str = str class hack_str(orig_str): def __new__(clazz, x=''): if isinstance(x, unicode): x = encoder(x)[0] elif not isinstance(x, orig_str): x = orig_str.__new__(clazz, x) pass return x pass pass orig_isinstance = isinstance def hack_isinstance(x, clss): if type(clss) is not tuple: return orig_isinstance(x, ((clss is not hack_str) and clss) or orig_str) clss = tuple([((cls is not hack_str) and cls) or orig_str for cls in clss]) return orig_isinstance(x, clss) __builtins__.str = hack_str __builtins__.isinstance = hack_isinstance locale.setlocale(locale.LC_CTYPE, '') charset = locale.getlocale(locale.LC_CTYPE)[1] encoder = codecs.getencoder(charset) }}} 執行這段程式之後,你的 $Python$ interpreter 就能依 locale 設定,順利執行大部分的 code 。但也有例外。例如呼叫 type(a) == str 或 a.__class__ == str 之類的程式碼。這些可以再透過 wrap type() ,和 str 的 special method 。但,這類的程式碼實在很少,一般都建議使用 isinstance() 判斷 object 的 class。 這個 work around ,相信在未來也成為多餘的。因為, str() 支援 locale 是必然的方向。 註: 用在 mod_python 上面時, __builtins__.xxx 必需改成 __builtins__['xxx'] 。
最後更新時間: 2007-01-26 00:35:14 CST |
引用
查詢:
COMMENTS: