หากมีความจำเป็นต้องหา 10 คำที่พบบ่อยที่สุดในชุดข้อมูล Python ช่วยให้เราหาได้โดยใช้โมดูล collections โมดูล collections มีคลาส counter ที่ให้จำนวนนับของคำหลังจากที่เราให้รายการคำไปยังมัน เรายังใช้เมธอด most_common เพื่อหาจำนวนคำดังกล่าวตามที่โปรแกรมอินพุตต้องการ
ตัวอย่าง
ในตัวอย่างด้านล่าง เราเอาย่อหน้าหนึ่ง แล้วสร้างรายการคำโดยใช้ split() เราจะใช้ counter() เพื่อหาจำนวนนับของทุกคำ สุดท้าย ฟังก์ชัน most_common จะให้ผลลัพธ์ที่เหมาะสมว่าต้องการคำกี่คำที่มีความถี่สูงสุด
from collections import Counter
word_set = "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. "
# สร้างรายการคำทั้งหมดในสตริง
word_list = word_set.split()
# หาจำนวนนับของแต่ละคำ
word_count = Counter(word_list)
# ใช้เมธอด most_common() จาก Counter subclass
print(word_count.most_common(3))
ผลลัพธ์
การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้:
[('words', 4), ('sometime', 3), ('what', 3)]