Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tìm tần suất từ trong chuỗi Python


Là một phần của phân tích văn bản, ta thường cần đếm từ và gán trọng số cho các thuật toán. Bài này chỉ cách tìm tần suất mỗi từ trong câu. Có 3 cách như sau.

Dùng Counter

Dùng Counter() từ module collections. Áp dụng split() tách từ, rồi most_common().

Ví dụ

from collections import Counter
line_text = "Learn and practice and learn to practice"
freq = Counter(line_text.split()).most_common()
print(freq)

Kết quả

[('and', 2), ('practice', 2), ('Learn', 1), ('learn', 1), ('to', 1)]

Dùng FreqDist()

NLTK cung cấp FreqDist cho thấy số từ và số từ riêng biệt. most_common() cho tần suất mỗi từ.

Ví dụ

from nltk import FreqDist
text = "Learn and practice and learn to practice"
words = text.split()
fdist1 = FreqDist(words)
print(fdist1)
print(fdist1.most_common())

Kết quả

<FreqDist with 5 samples and 7 outcomes>
[('and', 2), ('practice', 2), ('Learn', 1), ('learn', 1), ('to', 1)]

Dùng Dictionary

Lưu từ vào dictionary, dùng count() lấy tần suất, zip từ với tần suất. Kết quả là dictionary.

Ví dụ

text = "Learn and practice and learn to practice"
words = text.split()
wfreq = [words.count(w) for w in words]
print(dict(zip(words, wfreq)))

Kết quả

{'Learn': 1, 'and': 2, 'practice': 2, 'learn': 1, 'to': 1}