開始使用免費開始

使用你的子類別

多虧了繼承的威力,你得以在父類別 Document 的基礎上,建立一個功能豐富的 SocialMedia 類別。現在就來看看這些功能如何運作。

下方提供完整的 SocialMedia 定義供你參考。此外,為了方便使用,SocialMedia 已加入 __init__.py

class SocialMedia(Document):
    def __init__(self, text):
        Document.__init__(self, text)
        self.hashtag_counts = self._count_hashtags()
        self.mention_counts = self._count_mentions()

    def _count_hashtags(self):
        # Filter attribute so only words starting with '#' remain
        return filter_word_counts(self.word_counts, first_char='#')      

    def _count_mentions(self):
        # Filter attribute so only words starting with '@' remain
        return filter_word_counts(self.word_counts, first_char='@')

本練習屬於課程

Python 的軟體工程原則

檢視課程

練習說明

  • import 你自訂的 text_analyzer 套件。
  • 將預先載入的 datacamp_tweets 物件作為 text,建立 SocialMedia 的實例並指定為 dc_tweets
  • 使用正確的 dc_tweets 屬性與 most_commonprint 出被提及次數最多的前 5 位使用者。
  • 使用 text_analyzerplot_counter() 方法,搭配正確的 dc_tweets 屬性,繪製資料中最常用的主題標籤圖表。

動手互動練習

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

# Import custom text_analyzer package
import ____

# Create a SocialMedia instance with datacamp_tweets
dc_tweets = ____(text=datacamp_tweets)

# Print the top five most mentioned users
print(dc_tweets.____.most_common(5))

# Plot the most used hashtags
text_analyzer.____(dc_tweets.____)
編輯並執行程式碼