DEV Community

Vee Satayamas
Vee Satayamas

Posted on

3 3

ลุงที่ใช้เป็นแต่ shell script พื้น ๆ และขี้เกียจเขียน Python เยอะ แต่ต้องมาเรียกโปรแกรมตัดคำ

18 มีนาคม 2562

ผมมักจะไปสร้าง script ด้วย Python สั้น ๆ ไว้ใน $HOME/bin หรือ /usr/local/bin ก็ได้ แล้วก็ chmod 755 <ชื่อไฟล์> แล้วก็จะได้เรียกจาก shell ได้เลย

ผมเขียนไว้ 3 ตัวตามนี้

/usr/local/bin/deepcut

#!/usr/bin/env python
# * mode: python-mode *

import deepcut
import json
import sys

for line in sys.stdin:
    line = line.strip()
    print(json.dumps(deepcut.tokenize(line)))
Enter fullscreen mode Exit fullscreen mode

/usr/local/bin/newmm

#!/usr/bin/env python
# * mode: python-mode *

from pythainlp.tokenize import word_tokenize

import json
import sys

for line in sys.stdin:
    line = line.strip()
    print(json.dumps(word_tokenize(line ,engine='newmm')))
Enter fullscreen mode Exit fullscreen mode

/usr/local/bin/wordcutpy

#!/usr/bin/env python
# * mode: python-mode *

from wordcut import Wordcut
import json
import sys

wordcut = Wordcut.bigthai()

for line in sys.stdin:
    line = line.strip()
    print(json.dumps(wordcut.tokenize(line)))
Enter fullscreen mode Exit fullscreen mode

เรียกใช้งาน

ใน shell จะเรียกเดี่ยว ๆ ก็ได้แบบ

$ newmm < file1.txt > file1.ndjson
Enter fullscreen mode Exit fullscreen mode

แต่ส่วนมากก็จะเรียกผ่าน for-loop เถื่อน ๆ แบบนี้

$ for x in *.txt; do newmm < $x > $x.ndjson; done
Enter fullscreen mode Exit fullscreen mode

พอได้ไฟล์มาก็เอาไปใช้กับภาษาอื่นต่อได้

/usr/local/bin/wcnt

#!/usr/bin/env ruby
# * mode: ruby-mode *

require "json"
require "csv"

h = Hash.new(0)
while gets
  JSON.parse($_.chomp)
    .each{|w| h[w.chomp] += 1}
end
h.to_a.each{|row| puts CSV::generate_line(row)}
Enter fullscreen mode Exit fullscreen mode

เวลาเรียกก็ไป pipe แบบนี้เลย

cat file1.txt | newmm | wcnt
Enter fullscreen mode Exit fullscreen mode

เดี๋ยวนี้คนดี ๆ เขาคงใช้ Jupyter กันหมดแล้ว ผมก็พยายามฝึกอยู่เหมือนกัน แต่ยังไม่คล่อง บางทีก็เลยเอาแบบนี้ไปก่อน

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs