でーたさいえんすって何それ食えるの?

JuliaとかRとかPythonとかと戯れていたい

mecab-pythonモジュールを使わずにpythonからmecabで処理する方法

mecab-pythonのインストールでエラー吐いて、インストール問題解決に時間がかかった。。。 簡単な関数をつくって回避したので備忘録がてら、残しておく

import os
import codecs
import pandas as pd
import subprocess

def extract_words(s, exclude_keys=['記号', '助詞', '助動詞', '数'], genkei=False):
  """
  @type s: str
  @param x: mecabに処理をかけたい文字列
  
  @param exclude_keys: 除外したい品詞を指定. 除外しない場合は空のリストを指定する
  
  @param genkei: 返す単語の活用を原形に戻す場合はTrueにする
  
  @return: MeCabで処理をかけた結果をDataFrameとして返却
  """
  # 一時的にファイルに書き出し
  dirname_tmp = './tmp_process'
  fn_tmp = os.path.join(dirname_tmp, 'mecab_tmp.txt')
  
  fp = codecs.open(fn_tmp, 'w', 'utf8')
  fp.write(s+"\n")
  fp.close()
  
  # 書き出したファイルをMeCabに食わせて結果を拾う
  cmd = 'mecab ' + fn_tmp + ' -b 10000000'
  mecab_result = subprocess.check_output(cmd, shell=True).decode()
   
  # MeCab処理結果をdataframeにするための前処理
  mecab_result = mecab_result.replace('EOS', '')
  mecab_result = mecab_result.split('\n')
  mecab_result = [s.replace('\r', '') for s in mecab_result]
  mecab_result = [s for s in mecab_result if s != '']
  mecab_result = [s.split('\t') for s in mecab_result ]

  # DataFrameに変換
  df_mecab_result = pd.DataFrame( [ [s[0]] + s[1].split(',') for s in mecab_result] )
  # Exclude_keysで指定した品詞を除外
  df_mecab_result = df_mecab_result.loc[~df_mecab_result[1].isin(exclude_keys)]
  df_mecab_result = df_mecab_result.reset_index(drop=True)
  
  # genkeiフラグがTrueのときは7列目にある原形を返すようにする
  if genkei:
    df_words = df_mecab_result[7]
  else:
    df_words = df_mecab_result[0]
  
  for i in range(df_words.shape[0]):
    if df_words[i] == "*":
      df_words[i] = df_mecab_result[0][i]
  
  return(df_words)  

例えば

extract_words("neologdでいろいろやってみたい", exclude_keys=[], genkei=True) 

とやると、品詞で除外はせず動詞の活用は原形にした単語ベクトルが得られて次のようになる。

0    NEologd
12       いろいろ
3         やる
45         みる
6         たい