使用你的子類別
多虧了繼承的威力,你得以在父類別 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_common,print出被提及次數最多的前5位使用者。 - 使用
text_analyzer的plot_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.____)