시작하기무료로 시작하기

클래스 기능 활용하기

이제 Document 클래스의 __init__ 메서드에 텍스트를 자동으로 전처리하는 기능을 추가했어요. 이번 연습에서는 실제 사용자 입장에서 여러분의 작업이 어떤 이점을 주는지 확인해 보겠습니다.

아래에 복사된 Document 클래스가 여러분의 환경에 로드되어 있어요(방금 추가한 업데이트 포함).

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)

이 연습은 강의의 일부입니다

Python으로 배우는 소프트웨어 공학 원칙

강의 보기

연습 안내

  • 환경에 로드된 datacamp_tweets 데이터셋에서 새로운 Document 인스턴스를 생성하세요. datacamp_tweets 객체는 DataCamp와 DataCamp 사용자들이 작성한 수백 개의 트윗이 담긴 하나의 문자열입니다.
  • datacamp_doctokens 중 처음 5개를 출력하세요.
  • Document.__init__ 메서드에서 비공개 메서드 _count_words()로 자동 계산된 가장 흔한 단어 5개를 출력하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

# create a new document instance from datacamp_tweets
datacamp_doc = ____(____)

# print the first 5 tokens from datacamp_doc
print(____.____[:5])

# print the top 5 most used words in datacamp_doc
print(____.____.most_common(5))
코드 편집 및 실행