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

Đếm số lần xuất hiện của từ trong chuỗi Python

Đếm tần suất của một từ (word) trong chuỗi. Tách chuỗi thành từ bằng split(), so sánh chính xác.

Thuật toán

  1. Tách chuỗi: words = string.split() (mặc định tách whitespace).
  2. Khởi tạo count = 0.
  3. Duyệt list từ: nếu từ == từ cần tìm → count++.
  4. In count.

Mã nguồn

string = "I am programmer. I am student."
word = "am"

words = string.split()
count = 0
for w in words:
    if w == word:
        count += 1
print(count)  # 2

Kết quả

2

Cách ngắn gọn: list.count()

count = string.split().count(word)
print(count)

Cách Counter (cho nhiều từ)

from collections import Counter
freq = Counter(string.split())
print(freq[word])        # 2
print(freq.most_common())# [('I', 2), ('am', 2), ('programmer.', 1), ('student.', 1)]

Lưu ý quan trọng

  • split() tách theo whitespace, giữ lại punctuation: "programmer." ≠ "programmer".
  • Để chính xác hơn: dùng regex re.findall(r'\bword\b', string) hoặc tiền xử lý strip punctuation.
  • Case-sensitive: "Am" ≠ "am". Dùng lower() nếu cần case-insensitive.

Ví dụ nâng cao: Case-insensitive, bỏ dấu câu

import re
from collections import Counter

text = "I am a programmer. I AM a student! Am I?"
word = "am"

# Tách từ chỉ chứa chữ cái/số, bỏ dấu câu
words = re.findall(r'\b\w+\b', text.lower())
count = words.count(word)
print(count)  # 3 (am, am, am)

Kết luận

Cách đơn giản: string.split().count(word). Cách chuyên nghiệp: regex + Counter cho xử lý ngôn ngữ tự nhiên (NLP).