วันนี้ ขอนำเสนอสคริปต์ไพธอนสำหรับนับตัวอักษรที่เราต้องการในประโยค สคริปต์นี้ผมได้มาจาก slide ชุดหนึ่ง หลังจากที่ได้ลองรันสคริปต์แล้วพบว่า สคริปต์นี้ทำงานได้ค่อนข้างดีเลยทีเดียว ซึ่งเค้าทำออกมาเป็นโมดูล นั่นก็หมายความว่า เพื่อนต้อง save ไฟล์นี้ไว้ที่โฟลเดอร์ C:\Python24\Lib ด้วยนะครับ
ชื่อไฟล์ WORD_FRE.py แล้วบันทึกไว้ที่ C:\Python24\Lib
import regex, string
word = regex.compile( "[" + string.letters + "]+" )
def countwords(text, pattern=word):
dict = {}
end = 0
try:
while 1:
first = pattern.search(text, end)
word = pattern.group(0)
end = len(word) + first
try:
dict[word] = dict[word] + 1
except KeyError:
dict[word] = 1
except regex.error:
pass # triggers when first index goes to -1, terminates loop.
items = []
for word in dict.keys():
items.append( (dict[word], word) )
items.sort()
items.reverse()
return items
# if run as a script, count words in stdin.
if __name__ == "__main__":
import sys
x = countwords( sys.stdin.read() )
s = map(str, x)
t = string.joinfields(s, "\n")
print t
จากนั้นให้เราเขียนไฟล์ไพธอนขึ้นมาอีกไฟล์หนึ่ง เพื่อจะทดลองเรียกโมดูล WORD_FRE ขึ้นมาทำงาน ในที่นี้ผมตั้งชื่อไฟล์ test.py ( จะ save ไว้ที่ไหนก็ได้ครับ สำหรับไฟล์นี้)
ชื่อไฟล์ test.py
import WORD_FRE
import regex
punctuations = regex.compile("[.,()!\"-?]")
print WORD_FRE.countwords('"Hello!" said I. "Um, hello," she said.',punctuations)
>>>
[(4, '"'), (2, '.'), (2, ','), (1, '!')]
|

