统计一段文本中的名词
在本练习中,您将编写两个函数:nouns() 和 proper_nouns(),分别用于统计一段文本中普通名词与专有名词的数量。
这两个函数会接收一段文本,生成一个包含该文本中每个词词性标注(POS 标签)的列表。然后返回文本中专有名词/普通名词的计数。我们将在下一个练习中使用这些函数来分析假新闻并获得有趣的见解。
本练习中已将 en_core_web_sm 模型加载为 nlp。
本练习是课程的一部分
Python 中的 NLP 特征工程
交互式实操练习
通过完成这段示例代码来试试这个练习。
nlp = spacy.load('en_core_web_sm')
# Returns number of proper nouns
def proper_nouns(text, model=nlp):
# Create doc object
doc = model(text)
# Generate list of POS tags
pos = [token.pos_ for token in doc]
# Return number of proper nouns
return ____.____(____)
print(proper_nouns("Abdul, Bill and Cathy went to the market to buy apples.", nlp))