使用您的子类
借助继承的强大能力,您基于父类 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 中的软件工程原理
练习说明
import您的自定义包text_analyzer。- 将
dc_tweets定义为SocialMedia的一个实例,text参数使用预加载的datacamp_tweets对象。 - 使用合适的
dc_tweets属性,print数据中被提及最频繁的5个用户(most_common)。 - 使用
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.____)