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

Connected

แบบฝึกหัด

ใช้งานฟังก์ชันของคลาสที่สร้างขึ้น

ตอนนี้คุณได้เพิ่มฟังก์ชันการทำงานให้กับเมธอด __init__ ของคลาส Document แล้ว โดยระบบจะประมวลผลข้อความให้ผู้ใช้โดยอัตโนมัติ ในแบบฝึกหัดนี้ ให้ลองรับบทบาทเป็นผู้ใช้งานคลาสนี้เพื่อสัมผัสประโยชน์จากสิ่งที่สร้างขึ้นมา

คลาส Document (แสดงไว้ด้านล่าง) ถูกโหลดเข้าสู่ environment ของคุณแล้ว พร้อมกับการอัปเดตใหม่ทั้งหมด

class Document:
  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 with Counter
  def _count_words(self):
    return Counter(self.tokens)

คำแนะนำ

100 XP
  • สร้าง instance ใหม่ของ Document จากชุดข้อมูล datacamp_tweets ที่โหลดไว้ใน environment แล้ว โดย datacamp_tweets คือ string เดียวที่รวบรวมทวีตหลายร้อยรายการจาก DataCamp และผู้ใช้ DataCamp
  • แสดง tokens 5 รายการแรกจาก datacamp_doc
  • แสดง 5 คำที่พบบ่อยที่สุด ซึ่งคำนวณโดยเมธอด non-public _count_words() ที่ทำงานอัตโนมัติในเมธอด Document.__init__