ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมนับความถี่ของคำ (Word) ในสตริง
ตัวอย่าง
String: "I am programmer. I am student." Word: "am" Output: 2
อัลกอริทึม
1. กำหนดสตริงและคำที่ต้องการนับ 2. แยกสตริงเป็น list ของคำด้วย split() 3. ตัวแปร count = 0 4. วนลูป list: ถ้าคำตรงกับที่หา → count += 1 5. พิมพ์ count
โค้ดตัวอย่าง
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
วิธี替代: ใช้ list.count()
print(words.count(word))
วิธี替代: ใช้ collections.Counter
from collections import Counter print(Counter(words)[word])
สรุป
วิธีพื้นฐานใช้ loop และ split() วิธีสั้นกว่าใช้ list.count() หรือ Counter() เลือกตามความต้องการ หากมีข้อสงสัย สามารถถามได้ในส่วนความคิดเห็น