1. Learn
  2. /
  3. คอร์ส
  4. /
  5. หลักการวิศวกรรมซอฟต์แวร์ใน Python

Connected

แบบฝึกหัด

เพิ่มฟังก์ชันการทำงานให้กับ child class

คุณได้เขียนคลาส 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)

คำแนะนำ 1/2

undefined XP
    1
    2
  • ฟังก์ชัน filter_word_counts() ถูกโหลดไว้ในเซสชันแล้ว ใช้ help() เพื่อดูวิธีการใช้งานที่ถูกต้อง
  • เติมเมธอด _count_hashtags ให้สมบูรณ์โดยใช้ filter_word_counts() เพื่อให้เหลือเฉพาะ word_counts ที่ขึ้นต้นด้วย #