Direct Download Center

มาคุยกันก่อน


คลิกที่นี่ เข้ามารู้จักกันก่อน
Mr. P

สคริปต์ไพธอนนับตัวอักษรที่ต้องการ

โพสต์3 มี.ค. 2553, 7:04โดยWisit P.   [ อัปเดต 4 ก.พ. 2554, 18:49 ]
    วันนี้ ขอนำเสนอสคริปต์ไพธอนสำหรับนับตัวอักษรที่เราต้องการในประโยค สคริปต์นี้ผมได้มาจาก 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)

ให้ทดลองรันไฟล์นี้ที่ Pyscripter ครับ  จะได้ผลลัพธ์ดังนี้ครับ

>>> 
[(4, '"'), (2, '.'), (2, ','), (1, '!')]

ซึ่งเจ้าตัวโมดูล WORD_FRE จะทำการนับจำนวนตัวอักษรที่เรากำหนดไว้ที่ตัวแปร punctuations เพื่อนลองๆ ทำความเข้าใจโมดูลนี้ดูอีกครั้งครับ แล้วจะค่อยๆเข้าใจมากขึ้น สวัสดีครับ