使用您类的功能
您已经在 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_doc的前 5 个tokens。 - 打印在
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))