開始使用免費開始

為子類別加入功能

你剛剛寫了一個 SocialMedia 類別,會從 Document 繼承功能。現在 SocialMedia 還沒有和 Document 不同的功能。在這個練習中,你會替 SocialMedia 加上專門處理社群媒體資料的功能。

供你參考,以下是 Document 的定義。

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)

本練習屬於課程

Python 的軟體工程原則

檢視課程

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# 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 ____
編輯並執行程式碼