swath เป็นโปรแกรมตัดคำที่ดีโปรแกรมหนึ่ง เอา text อะไรยัดเข้าไปก็มักจะไม่เจ๊ง ไม่ต้องเขียนอะไรครอบมาก แต่ว่าบอกทีก็อยากใช้จาก python วีธีหลักที่จะเรียกใช้ ก็อาจจะสร้าง module ด้วย c++ ขึ้นมาเชื่อม swath กับ python วิธีแรกนี้โปรแกรมทำงานได้รวดเร็ว แต่ว่ามันเหนื่อยนะกว่าจะเสร็จ
ผมก็เลยใช้วิธีที่โปรแกรมทำงานช้าๆ แต่เขียนเสร็จเร็วแทน โดยเรียกผ่าน subprocess
import subprocess
def wordbreak(utxt):
if not isinstance(utxt, unicode):
raise TypeError, "wordbreak needs unicode"
tis_txt = utxt.encode("CP874", 'replace')
p = subprocess.Popen("swath", stdin = subprocess.PIPE, \
stdout = subprocess.PIPE, close_fds = True)
p.stdin.write(tis_txt)
p.stdin.close()
raw_output = p.stdout.read().decode("CP874", "replace")
words = raw_output.split("|")
p.stdout.close()
return words
# Copyright (c) 2010 Vee Satayamas
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
เวลาเรียกใช้ก็สั่ง wordbreak(u”ทดลองตัดคำ”) อะไรแบบนี้ได้ แล้ว wordbreak ก็จะ return list ของคำออกมา ผมใช้ python 2.5.x นะครับ
