Bắt đầu ngayBắt đầu miễn phí

Bổ sung chức năng cho lớp con

Bạn vừa viết một lớp SocialMedia kế thừa chức năng từ Document. Hiện tại, lớp SocialMedia chưa có gì khác so với Document. Trong bài tập này, bạn sẽ thêm các tính năng vào SocialMedia để chuyên biệt hóa nó cho dữ liệu mạng xã hội.

Để tham khảo, định nghĩa của Document được đưa ra bên dưới.

class Document:
    # Initialize a new Document instance
    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
    def _count_words(self):
        # Use collections.Counter to count the document's tokens
        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

Xem khóa học

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.

# Define a SocialMedia class that is a child of the `Document class`
class SocialMedia(Document):
    def __init__(self, text):
        Document.__init__(self, text)
        self.hashtag_counts = self._count_hashtags()
        
    def _count_hashtags(self):
        # Filter attribute so only words starting with '#' remain
        return ____
Chỉnh sửa và Chạy Mã