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

Loại bỏ từ dừng (stop words) với NLTK trong Python

Khi máy tính xử lý ngôn ngữ tự nhiên, một số từ cực kỳ phổ biến dường như ít giá trị trong việc chọn tài liệu phù hợp với nhu cầu người dùng bị loại khỏi từ điển hoàn toàn. Những từ này gọi là stop words.

Ví dụ, nếu cho câu đầu vào −

John is a person who takes care of the people around him.

Sau khi loại stop words, kết quả −

['John', 'person', 'takes', 'care', 'people', 'around', '.']

NLTK có bộ sưu tập stopwords dùng để loại từ câu cho trước. Nằm trong module NLTK.corpus. Ta dùng để lọc stop words. Ví dụ,

Ví dụ

from nltk.corpus import stopwords from nltk.tokenize import word_tokenize my_sent = "John is a person who takes care of people around him." tokens = word_tokenize(my_sent) filtered_sentence = [w for w in tokens if not w in stopwords.words()] print(filtered_sentence)

Kết quả

Điều này sẽ cho kết quả −

['John', 'person', 'takes', 'care', 'people', 'around', '.']