Dùng collections.Counter để đếm tần suất từ và lấy top K từ phổ biến nhất.
Ví dụ cơ bản
from collections import Counter text = """This is a series of strings to count many words. They sometime hurt and words sometime inspire. Also sometime fewer words convey more meaning than a bag of words. Be careful what you speak or what you write or even what you think of.""" # Tách từ (đơn giản: split whitespace) words = text.split() # Đếm tần suất word_counts = Counter(words) # Top 3 từ phổ biến nhất top_3 = word_counts.most_common(3) print(top_3)
Kết quả
[('words', 4), ('sometime', 3), ('what', 3)]
Cải tiến: Tiền xử lý văn bản thực tế
import re
from collections import Counter
def top_k_words(text, k=10):
# Lowercase, tách từ bằng regex (chỉ giữ chữ/số)
words = re.findall(r'\b\w+\b', text.lower())
# Loại stop words cơ bản (tuỳ chọn)
stop_words = {'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could', 'should', 'may', 'might', 'must', 'can', 'this', 'that', 'these', 'those', 'i', 'you', 'he', 'she', 'it', 'we', 'they', 'what', 'which', 'who', 'whom', 'whose', 'where', 'when', 'why', 'how'}
filtered = [w for w in words if w not in stop_words and len(w) > 1]
return Counter(filtered).most_common(k)
text = """Your long text here..."""
print(top_k_words(text, 10))
Lưu ý
split()đơn giản nhưng giữ punctuation: "words." ≠ "words"- Dùng
re.findall(r'\b\w+\b', text.lower())để tách từ chuẩn hơn - Cần loại stop words (the, and, is...) để kết quả có ý nghĩa
- Với dữ liệu lớn: dùng
Counter.update()xử lý chunk by chunk