Đếm tần suất xuất hiện của từng từ trong chuỗi. Sử dụng dictionary comprehension với split() và count().
Mã nguồn
my_str = 'Hi there Will, how are you Will, Will you say Hi to me'
print("Chuỗi:", my_str)
# Dictionary comprehension: key=từ, value=số lần xuất hiện
my_result = {key: my_str.count(key) for key in my_str.split()}
print("Tần suất từ:", my_result)
Kết quả
Chuỗi: Hi there Will, how are you Will, Will you say Hi to me
Tần suất từ: {'Hi': 2, 'there': 1, 'Will,': 2, 'how': 1, 'are': 1, 'you': 2, 'Will': 3, 'say': 1, 'to': 1, 'me': 1}
Giải thích
my_str.split()tách chuỗi thành list từ (mặc định tách theo whitespace).- Dictionary comprehension lặp qua từng từ
key. my_str.count(key)đếm số lầnkeyxuất hiện trong chuỗi gốc.- Lưu ý: "Will," và "Will" được coi là hai từ khác nhau do dấu phẩy.
Cải tiến: Xử lý dấu câu
import re
from collections import Counter
words = re.findall(r'\b\w+\b', my_str.lower()) # Chỉ lấy chữ/số, bỏ dấu câu, lower
my_result = Counter(words)
print(my_result)
# Counter({'will': 3, 'hi': 2, 'you': 2, 'there': 1, 'how': 1, 'are': 1, 'say': 1, 'to': 1, 'me': 1})
Dùng regex \b\w+\b để tách từ chính xác, Counter hiệu quả hơn count() lặp lại.