n-gram、共起ネットワーク(1)

環境設定

Google colaboratoryで実行できます

本プログラムに必要なライブラリをインストールします

  1. #環境設定

  2. !pip install janome

  3. !pip install wikipedia

  4. !pip install japanize-matplotlib

  5. !pip install nlplot

(1)Wikipediaから指定したキーワードに関するページの文章を読み込みます。

keywordで指定した単語に関するページをWikipediaで検索して、その中から、keyword_indexで指定したページを読み込みます。

  1. #Wikipediaからのテキスト読み込み


  2. from janome.tokenizer import Tokenizer

  3. t = Tokenizer()

  4. import wikipedia


  5. keyword = "\u5728\u5B85\u533B\u7642"#@param{type:"string"}


  6. wikipedia.set_lang("ja")

  7. search_response = wikipedia.search(keyword)

  8. for sr in search_response:

  9. print(search_response.index(sr),sr)

  10. keyword_index=0#@param{type:"number"}

  11. print('読み込みページ:',search_response[keyword_index])

  12. page_data = wikipedia.page(search_response[keyword_index])

  13. docs=page_data.content


  14. docT=docs.replace('\n','').split('。')


  15. #読み込んだ文章の分かち書き(名詞のみ)


  16. from collections import Counter

  17. import collections

  18. import re


  19. word=[]

  20. for d in docT:

  21. dd=""

  22. for token in t.tokenize(d):

  23. if re.match('名詞', token.part_of_speech):

  24. dd+=" "+token.surface

  25. word.append(dd)


  26. import pandas as pd

  27. df=pd.DataFrame(word,columns={"text"})

  28. print(df)

(2)n-gram(n個の連続する単位(n-gram)での単語出現回数)のn値を変えながら、連続した単語(名詞)の出現回数を可視化してください。

ngramで指定した個数をn値とします

  1. #n-gramの表示


  2. import nlplot

  3. npt = nlplot.NLPlot(df, target_col='text')

  4. ngram=1#@param{type:"integer"}

  5. npt.bar_ngram(

  6. ngram=ngram,

  7. top_n=20,

  8. width=800,

  9. height=600,)

(3)ストップワード(出現頻度の高すぎる単語の除去)の設定をしてください。

top_nで指定した出現頻度の高い単語を除去します。

  1. #ストップワード(出現頻度の高すぎる単語の除去)の設定


  2. top_n=0#@param{type:"integer"}

  3. stopwords = npt.get_stopword(top_n=top_n, min_freq=0)

  4. print(stopwords)

(4)共起語(あるキーワードに対して頻繁に出現する単語)算出のためのパラメータ(min_edge_frequecy)を設定してください。node_size(円):50程度, edge_size(線):100程度を目安としてください。

  1. #共起語の算出設定


  2. min_edge_frequency=2#@param{type:"integer"}


  3. npt.build_graph(stopwords=stopwords,min_edge_frequency=min_edge_frequency)


  4. display(

  5. npt.node_df.head(npt.node_df.shape[0]), npt.node_df.shape,

  6. npt.edge_df.head(npt.edge_df.shape[0]), npt.edge_df.shape

  7. )

(5)パラメータ(min_edge_frequecy)を調整しながら、「在宅医療」のWikipediaのページについての共起ネットワークを描画して、その結果から「読み取れた内容(文章)」を回答してください。また、Wikipediaのページを直接読解した内容とを比較して、共起ネットワークから「読み取れなかった重要な内容(文章)」を回答してください。

  1. #共起ネットワークの描画


  2. npt.co_network(

  3. title='Co-occurrence network',

  4. width=800,

  5. height=600,)

北海道医療大学・情報センター