Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Program: นับจำนวนคำใน String (Count Words)

นับจำนวนคำ (Words) ใน String ที่กำหนด มีหลายวิธีใน Python

วิธีที่ 1: ใช้ str.split() (แนะนำ - เรียบง่ายที่สุด)

def count_words(text: str) -> int:
    """นับคำโดยแยกด้วย Whitespace (Space, Tab, Newline)"""
    return len(text.split())

# ทดสอบ
text = "Python is a high level language. Python is interpreted language. Python is general-purpose programming language"
print("Word count:", count_words(text))  # 16

ผลลัพธ์

Word count: 16

str.split() โดยไม่ระบุ Argument จะแยกด้วย Whitespace ใดๆ (Space, Tab, Newline) และตัด Empty Strings ออกอัตโนมัติ

วิธีที่ 2: ใช้ For Loop (Manual Counting)

def count_words_loop(text: str) -> int:
    if not text:
        return 0
    
    count = 1  # เริ่มที่ 1 (คำแรก)
    for char in text:
        if char in (' ', '\n', '\t'):
            count += 1
    return count

print(count_words_loop(text))  # 16

วิธีที่ 3: ใช้ While Loop

def count_words_while(text: str) -> int:
    if not text:
        return 0
    
    count = 1
    i = 0
    while i < len(text):
        if text[i] in (' ', '\n', '\t'):
            count += 1
        i += 1
    return count

วิธีที่ 4: ใช้ Regular Expression (Regex)

import re

def count_words_regex(text: str) -> int:
    # หา Word Boundaries: \w+ match ตัวอักษร/ตัวเลข/Underscore
    words = re.findall(r'\b\w+\b', text)
    return len(words)

print(count_words_regex(text))  # 16

วิธีที่ 5: นับคำเฉพาะเจาะจง (Count Specific Word)

def count_specific_word(text: str, target: str) -> int:
    """นับจำนวนครั้งที่ target word ปรากฏ (Case-insensitive)"""
    words = text.lower().split()
    target = target.lower()
    return words.count(target)

text = "Python is great. Python is powerful. I love Python."
print(count_specific_word(text, "Python"))  # 3
print(count_specific_word(text, "is"))      # 2

ผลลัพธ์

3
2

ข้อควรระวัง

  • split() นับ "don't" เป็น 1 คำ (ไม่แยก Apostrophe)
  • split() นับ "hello,world" เป็น 1 คำ (ไม่มี Space)
  • สำหรับ NLP จริง ควรใช้ nltk.word_tokenize() หรือ spaCy
  • Thai Language ต้องใช้ Tokenizer เฉพาะ (เช่น pythainlp) เพราะไม่มี Space คั่นคำ

สรุป

MethodProsCons
len(text.split())Simple, Fast, Built-inไม่จัดการ Punctuation ได้ดี
Manual Loopควบคุม Logic เองได้Verbose, Error-prone
RegexFlexible Patternช้ากว่า, Complex
NLTK/spaCyAccurate for NLPHeavy Dependency