Sử dụng lớp con của bạn
Nhờ sức mạnh của kế thừa, bạn đã tạo được một lớp SocialMedia giàu tính năng dựa trên lớp cha Document. Hãy xem một vài tính năng này hoạt động ra sao.
Bên dưới là toàn bộ định nghĩa của SocialMedia để bạn tham khảo. Ngoài ra, SocialMedia đã được thêm vào __init__.py để tiện sử dụng.
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='@')
Bài tập này là một phần của khóa học
Nguyên tắc Kỹ thuật Phần mềm với Python
Hướng dẫn bài tập
importgói tùy chỉnhtext_analyzercủa bạn.- Khai báo
dc_tweetslà một thể hiện củaSocialMediavới đối tượngdatacamp_tweetsđã được nạp sẵn làmtext. print5người dùng được nhắc đếnmost_commontrong dữ liệu bằng cách dùng thuộc tính phù hợp củadc_tweets.- Dùng phương thức
plot_counter()củatext_analyzerđể vẽ các hashtag được dùng nhiều nhất trong dữ liệu bằng cách dùng thuộc tính phù hợp củadc_tweets.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
# 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.____)