始める無料で始める

テキスト中の名詞を数える

この演習では、テキスト中の普通名詞と固有名詞の数をそれぞれ数える関数 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))
コードを編集して実行