Giới thiệu
Để tìm từ (word) xuất hiện nhiều nhất trong một list các câu (strings), ta tách từng câu thành từ, đếm tần suất bằng defaultdict, sau đó dùng max() với key là hàm get của dict.
Ví dụ minh họa
from collections import defaultdict
my_list = ["python is best for coders", "python is fun", "python is easy to learn"]
print("Danh sách câu:")
print(my_list)
my_temp = defaultdict(int)
for sub in my_list:
for word in sub.split():
my_temp[word] += 1
result = max(my_temp, key=my_temp.get)
print("Từ có tần suất cao nhất:")
print(result)
Kết quả đầu ra
Danh sách câu: ['python is best for coders', 'python is fun', 'python is easy to learn'] Từ có tần suất cao nhất: python
Giải thích
defaultdict(int)tự động khởi tạo giá trị 0 cho key mới.sub.split()tách câu thành list từ (mặc định split theo whitespace).max(dict, key=dict.get)trả về key có value lớn nhất.- Từ "python" xuất hiện 3 lần, "is" 3 lần, nhưng max trả về key đầu tiên gặp trong dict (python).