นำ child class ไปใช้งาน
ด้วยพลังของการสืบทอด (inheritance) คุณสามารถสร้างคลาส SocialMedia ที่มีฟีเจอร์ครบครันจากคลาสแม่ Document ได้ มาลองใช้ฟีเจอร์เหล่านั้นกันดูครับ
ด้านล่างคือนิยามเต็มของ 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ที่สร้างขึ้นเอง- กำหนดให้
dc_tweetsเป็น instance ของSocialMediaโดยใช้ออบเจ็กต์datacamp_tweetsที่โหลดไว้แล้วเป็นtext printรายชื่อผู้ใช้ที่ถูก mention บ่อยที่สุด5อันดับแรกจากข้อมูล โดยใช้ attribute ที่เหมาะสมของdc_tweets- ใช้เมธอด
plot_counter()ของtext_analyzerเพื่อพล็อต hashtag ที่ถูกใช้มากที่สุดในข้อมูล โดยใช้ attribute ที่เหมาะสมของ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.____)