ดัดแปลงโค๊ดมาจาก programming is hard: isThai and ThaiWarp function
import PyICU
def isThai(chr):
cVal = ord(chr)
if(cVal >= 3584 and cVal <= 3711):
return True
return False
def wrap(txt):
txt = PyICU.UnicodeString(txt)
bd = PyICU.BreakIterator.createWordInstance(PyICU.Locale("th"))
bd.setText(txt)
lastPos = bd.first()
retTxt = PyICU.UnicodeString("")
txt_list = []
try:
while(1):
currentPos = bd.next()
retTxt += txt[lastPos:currentPos]
#
txt_list.append(txt[lastPos:currentPos])
#Only thai language evaluated
if(isThai(txt[currentPos-1])):
if(currentPos < len(txt)):
if(isThai(txt[currentPos])):
#This is dummy word seperator
#retTxt += PyICU.UnicodeString("|||")
#
pass
lastPos = currentPos
except StopIteration:
pass
#retTxt = retTxt[:-1]
#return retTxt
return [unicode(i) for i in txt_list]
def fullwrap(txt):
txt_list = txt.split(' ')
new_list = []
for i in txt_list:
#new_list.extend(wrap(i).split('|||'))
new_list.extend(wrap(i))
return new_list
ลองตัดคำดู
$ python
Python 2.4.4 (#2, Jan 13 2007, 17:50:26) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> word = 'ทดลองเรียน Python ภาษาโปรแกรมคอมพิวเตอร์' >>> print wrap(word) ทดลอง|||เรียน Python ภาษา|||โปรแกรม|||คอมพิวเตอร์ >>> print fullwrap(word) [u'\u0e17\u0e14\u0e25\u0e2d\u0e07', u'\u0e40\u0e23\u0e35\u0e22\u0e19', u'Python', u'\u0e20\u0e32\u0e29\u0e32', u'\u0e42\u0e1b\u0e23\u0e41\u0e01\u0e23\u0e21', u'\u0e04\u0e2d\u0e21\u0e1e\u0e34\u0e27\u0e40\u0e15\u0e2d\u0e23\u0e4c'] >>> for i in fullwrap(word): print i ... ทดลอง เรียน Python ภาษา โปรแกรม คอมพิวเตอร์ >>>