Sử dụng chức năng của lớp bạn
Giờ đây bạn đã bổ sung thêm chức năng vào phương thức __init__ của lớp Document để tự động xử lý văn bản cho người dùng. Trong bài tập này, bạn sẽ đóng vai một trong những người dùng đó để thấy lợi ích từ công sức bạn bỏ ra.
Lớp Document (sao chép bên dưới) đã được nạp vào môi trường của bạn (bao gồm cả các cập nhật mới).
class Document:
def __init__(self, text):
self.text = text
# pre tokenize the document with non-public tokenize method
self.tokens = self._tokenize()
# pre tokenize the document with non-public count_words
self.word_counts = self._count_words()
def _tokenize(self):
return tokenize(self.text)
# non-public method to tally document's word counts with Counter
def _count_words(self):
return Counter(self.tokens)
Bài tập này là một phần của khóa học
Nguyên tắc Kỹ thuật Phần mềm với Python
Hướng dẫn bài tập
- Tạo một thực thể
Documentmới từ tập dữ liệudatacamp_tweetsđã được nạp vào môi trường của bạn. Đối tượngdatacamp_tweetslà một chuỗi đơn chứa hàng trăm tweet do DataCamp và người dùng DataCamp viết. - In 5
tokensđầu tiên từdatacamp_doc. - In 5 từ xuất hiện nhiều nhất đã được tính tự động bởi phương thức không công khai
_count_words()trongDocument.__init__.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
# create a new document instance from datacamp_tweets
datacamp_doc = ____(____)
# print the first 5 tokens from datacamp_doc
print(____.____[:5])
# print the top 5 most used words in datacamp_doc
print(____.____.most_common(5))