LoginSignup
10
19

More than 5 years have passed since last update.

MeCab(python)によるキーワード抜き出し

Posted at

ここにExcelファイルがある。
とあるDBから出力されたもので、1行1レコード、一つのフィールドには文章が格納されている。
今回のお題は、このフィールド内の文章からよく使われるキーワードを抜き出して、キーワードごとに出現回数を数え、順位付けを行ってみよう、というもの。

入口と出口はWindowsのExcelファイルで、中間はMacで行う。

用意するもの

いつもの自分の環境で行う。

  • Mac
  • python
  • MeCab
  • nkf

後々pandasでデータ処理するつもりなので、utf-8にしたり、pandasを使ったりしている。

該当のxlsファイルからcsvに出力する

これはExcelのメニューから。
test.xls -> test.csv

文字コードをsjisからutf-8に変更する

$ nkf -g test.csv
Shift_JIS
$ nkf -w test.csv > test_utf8.csv
$ nkf -g test_utf8.csv
UTF-8

pythonでcsvを読み込む

import pandas as pd 

csv_file = 'test.csv'
df = pd.read_csv(csv_file, encoding='utf-8', header=1)

名詞、動詞ごとに分解してカウントする

mecabのインストール

brew search mecab

pip search mecab
pip install mecab-python 

...
Successfully installed mecab-python-0.996
と出てOKぽい。
これで、python(2.x系)で使えるようになった。

import MeCab

def count_word(df):
    e = df[u'コメント']
    dic_n = {}
    dic_v = {}
    m = MeCab.Tagger('-Ochasen')    # 出力をChasenモードにする

    for s in e:
        if type(s) != unicode:
            continue
        s8 = s.encode('utf-8')
        print s8
        node = m.parseToNode(s8)
        while node:
            word=node.feature.split(',')[0]
            key = node.surface
            if word=='名詞':
                dic = dic_n
                print "<", key, "> (n)"
            elif word=='動詞':
                dic = dic_v
                print "<", key, "> (v)"
            else:
                node = node.next
                continue
            if dic.has_key(key):
                dic[key] += 1
            else:
                dic[key] = 1
            node = node.next
    return dic_n, dic_v

出現回数に多い順に並べてcsvに書き出す(utf-8)

import csv

def write_to_csv(dic, csv_file):
    f = open(csv_file, 'w')
    writer = csv.writer(f, lineterminator='\n')

    # Valueの値でソートする
    for k,v in sorted(dic.items(), key=lambda x:x[1], reverse=True):
        print k, v
        writer.writerow([k, v])
    f.close()

write_to_csv(dic_n, 'test_dic_n_utf8.csv')
write_to_csv(dic_v, 'test_dic_v_utf8.csv')

sjisに変換する

$ nkf -g test_dic_n_utf8.csv 
UTF-8
$ nkf -s test_dic_n_utf8.csv > test_dic_n_sjis.csv
$ nkf -g test_dic_n_sjis.csv 
Shift_JIS

xls形式に変換する

test_dic_n_sjis.csv をExcelで開いて、xlsで保存する。

おわり。

参考サイト

http://qiita.com/tstomoki/items/f17c04bd18699a6465be
http://qiita.com/ysk_1031/items/7f0cfb7e9e4c4b9129c9
http://salinger.github.io/blog/2013/01/17/1/ 1


  1. このサイトに注意点があったのでメモ。 MeCabでUnicode文字列を扱う場合は、一度エンコードする必要がある。この際、node = tagger.parseToNode(string.encode("utf-8"))とすると、stringがパース中にガベコレされてしまって、変な挙動になる場合があるので注意。このように一度変数に代入すれば問題ない。 

10
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
19