Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

หาความถี่คำ (Word Frequency) ในสตริง Python

Text Analytics ต้องนับความถี่คำ บทความนี้เสนอ 3 วิธี

1. collections.Counter (แนะนำ)

from collections import Counter

text = "Learn and practice and learn to practice"
freq = Counter(text.split()).most_common()
print(freq)
# [('and', 2), ('practice', 2), ('Learn', 1), ('learn', 1), ('to', 1)]

2. NLTK FreqDist

from nltk import FreqDist

text = "Learn and practice and learn to practice"
words = text.split()
fdist = FreqDist(words)
print(fdist.most_common())
# [('and', 2), ('practice', 2), ('Learn', 1), ('learn', 1), ('to', 1)]

3. Dictionary + count()

text = "Learn and practice and learn to practice"
words = text.split()
wfreq = [words.count(w) for w in words]
print(dict(zip(words, wfreq)))
# {'Learn': 1, 'and': 2, 'practice': 2, 'learn': 1, 'to': 1}

เปรียบเทียบ

วิธีCase SensitivePerformanceDependencies
CounterYesO(n)Built-in
FreqDistYesO(n)NLTK
Dict + countYesO(n²)Built-in

แนะนำ: ใช้ Counter สำหรับ General Purpose, ใช้ FreqDist สำหรับ NLP Pipeline

Tip: ใช้ text.lower().split() ถ้าต้องการ Case-insensitive