Aan de slagGa gratis aan de slag

Je kindklasse gebruiken

Dankzij de kracht van overerving kon je een uitgebreide SocialMedia-klasse maken op basis van de ouderklasse Document. Laten we enkele van deze features in actie bekijken.

Hieronder staat ter referentie de volledige definitie van SocialMedia. Daarnaast is SocialMedia toegevoegd aan __init__.py voor het gemak.

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='@')

Deze oefening maakt deel uit van de cursus

Software-engineeringprincipes in Python

Cursus bekijken

Oefeninstructies

  • import je eigen text_analyzer-pakket.
  • Definieer dc_tweets als een instantie van SocialMedia met het vooraf geladen object datacamp_tweets als text.
  • print de 5 most_common gebruikers met de meeste vermeldingen in de data via het juiste attribuut van dc_tweets.
  • Gebruik de methode plot_counter() van text_analyzer om de meest gebruikte hashtags in de data te plotten via het juiste attribuut van dc_tweets.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# 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.____)
Code bewerken en uitvoeren