開始使用免費開始

統計一段文字中的名詞數量

在這個練習中,你會撰寫兩個函式,nouns()proper_nouns(),分別用來計算一段文字中普通名詞與專有名詞的數量。

這些函式會接收一段文字,產生一個清單,裡面包含每個詞的詞性標註(POS tags)。接著回傳該文字中專有名詞/普通名詞的數量。我們會在下一個練習中使用這些函式,來對假新聞做一些有意思的分析。

在本練習中,en_core_web_sm 模型已經以 nlp 名稱載入。

本練習屬於課程

Python 中文本特徵工程

檢視課程

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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))
編輯並執行程式碼