ちょっとだけテキストマイニング-形態素解析
例えばチャットbotを作るとき、どの単語をどの文章ラベルとして登録すればいいのか迷ったりしませんか?
最近はなんとなくで教師データを入れておけば、自動的に学習してくれますが、一度自分で分析しておくことで、なんとなく関係性を確認することができると思います。
ということで、簡単な文章分析(自然言語処理)を行なっていく方法を書いておきます。
使用するデータ
今回使用するデータは、HPに落ちているよくある質問やQ&Aの文章を使用していきます。
(私はよくあるご質問/袋井市ホームページを参考に作成)
以下のようなcsvデータを作成します。名前はfaq.csvとします。
Pythonでプログラム
今回は、Pythonの勉強も兼ねて作成を行なっています。
プログラムは以下の通りです。後で詳しく説明します。
import csv import pprint import pandas as pd #使用データ with open('faq.csv') as f: reader = csv.reader(f) list_data = [row for row in reader] print(list_data) csv_input = pd.read_csv(filepath_or_buffer="大学のFAQについて2.csv", sep=",") print(csv_input[['質問内容','ラベル']]) #Janomeのインストール #!pip install janome from janome.tokenizer import Tokenizer import collections t = Tokenizer() #形態素解析 for index , csv_input in list_data: print(index) for token in t.tokenize(index): print(token) print('-----------------------------------------') import collections #単語語数のみ拾う for index, csv_input in list_data: print(csv_input+' : '+ index) c = collections.Counter(t.tokenize(index, wakati=True)) print(c) print([token.surface for token in t.tokenize(index) if token.part_of_speech.startswith('名詞') or token.part_of_speech.startswith('動詞')]) print('-----------------------------------------') import collections #分析するラベル label = '介護' labeltoken = list() for index, csv_input in list_data: if csv_input == label: print(csv_input+' : '+ index) for token in t.tokenize(index): if token.part_of_speech.startswith('名詞') or token.part_of_speech.startswith('動詞'): print(token.surface) labeltoken.append(token.surface) print('-----------------------------------------') print(labeltoken) from collections import Counter c = Counter(labeltoken) print(c) #!pip install japanize-matplotlib import numpy as np import matplotlib.pyplot as plt import japanize_matplotlib plt.figure(figsize=(36, 15), dpi=100) left = np.array(list(c.keys())) height = np.array(list(c.values())) plt.bar(left, height)
データの取り込み
csvデータを取り込みます。プログラムでは2種類の取り込み方法を書いていますが、分析に使用しているのは下記のものです。
形態素解析のツールインポート
今回は、Janomeというアプリケーションを使用して形態素解析します。
インストールをしていない場合はインストールします。
mocobeta.github.io
簡単に分析する方法としておすすめ
簡単にテキストマイニングしてくれるサイトがあります。今回は複数種類のデータを分析する方法について書きましたが、1種類のみであれば以下のサイトがおすすめです。(プログラムも書かなくていい!)
textmining.userlocal.jp
今回使用したデータの"ごみ・リサイクル"というラベルのデータを分析すると以下のようになりました。
AIテキストマイニング by ユーザーローカル
ワードクラウド(出現しやすい単語を表示)以外にも共起ネットワークを表示してくれるので、単語ごとの関係性がわかりやすいです。