자식 클래스를 사용해 보기
상속의 힘 덕분에 부모 클래스인 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으로 배우는 소프트웨어 공학 원칙
연습 안내
- 사용자 정의 패키지
text_analyzer를import하세요. - 미리 로드된 객체
datacamp_tweets를text로 사용하여SocialMedia의 인스턴스dc_tweets를 정의하세요. - 적절한
dc_tweets속성을 사용해 데이터에서 언급(멘션)이 가장 많은 사용자5명의most_common을print하세요. 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.____)