Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Đếm từ trong chuỗi Python (Count words in string)

Đếm số từ trong chuỗi: tách bằng whitespace (space, tab, newline).

Phương pháp 1: Dùng split() (Khuyên dùng - đơn giản, đúng chuẩn)

text = "Python is a high level language. Python is interpreted."
words = text.split()  # Mặc định tách theo bất kỳ whitespace nào
print(len(words))     # 10

Phương pháp 2: Vòng lặp for (thủ công)

test_string = input("String: ")
total = 1 if test_string else 0
for ch in test_string:
    if ch in (' ', '\n', '\t'):
        total += 1
print("Total words:", total)

Phương pháp 3: Vòng lặp while

test_string = input("String: ")
total = 1 if test_string else 0
i = 0
while i < len(test_string):
    if test_string[i] in (' ', '\n', '\t'):
        total += 1
    i += 1
print("Total words:", total)

Phương pháp 4: Hàm tự định nghĩa

def count_words(text):
    if not text:
        return 0
    return len(text.split())

# Hoặc thủ công
def count_words_manual(text):
    count = 0
    in_word = False
    for ch in text:
        if ch.isspace():
            in_word = False
        elif not in_word:
            in_word = True
            count += 1
    return count

So sánh

CáchƯu điểmNhược điểm
str.split()Đơn giản, đúng chuẩn Unicode, xử lý multi-spaceTạo list tạm (memory)
Regex re.findall(r'\S+')Linh hoạt patternChậm hơn split
Manual loopO(1) space, streamingCode dài, dễ sai

Đếm từ cụ thể (word frequency)

from collections import Counter
import re

text = "Python is great. Python is fun. I love Python."
words = re.findall(r'\b\w+\b', text.lower())
freq = Counter(words)
print(freq.most_common(3))
# [('python', 3), ('is', 2), ('great', 1)]

Lưu ý

  • split() không tham số: tách theo bất kỳ whitespace (space, tab, newline, \r, \f, \v) và bỏ qua chuỗi rỗng.
  • split(' ') chỉ tách theo space đơn -> giữ chuỗi rỗng nếu nhiều space liên tiếp.
  • Với tiếng Việt/Unicode: split() hoạt động tốt.