LoginSignup
2
2

More than 5 years have passed since last update.

Python3+xlrd+mecabを利用してExcelデータを分かち書きで出力

Last updated at Posted at 2017-04-06

目的

Excelファイルにテキストデータが存在し、そのテキストデータを分かち書きしたものをタブ区切り形式(tsvファイル)で出力する。

動作確認環境

Mac OS 10.12.3
Python 3.6.0
mecab of 0.996
mecab-python3==0.7

準備

mecabと辞書をインストール

Homebrewでのインストール(Mac)
 Python3からMeCabを使う
もしくは、自分でmakeしてインストール
 Python3で形態素解析エンジンMeCabを使えるようにする(2016年3月版)

pythonバインディングのインストール

 Python3でmecabを使う

xlrdのインストール

 【Python】pandasでExcelを読み込む

ソースコード

mecab.py
#!/usr/bin/env python

import xlrd
import MeCab
import sys

args = sys.argv

# Excelファイルを開く
book = xlrd.open_workbook(args[1])
sh = book.sheet_by_index(0)

# header
print("\t".join(('text','price')))

# 分かち書きオプションでパース
t = MeCab.Tagger ("-Owakati")

# 各行について
for rx in range(1, sh.nrows):

    # 必要なカラムを拾う
    text = sh.cell_value(rowx=rx, colx=1)
    price = sh.cell_value(rowx=rx, colx=2)

    # 改行削除
    text = text.replace('\n','').replace('\r','')

    try:
        # パースと改行削除
        m = t.parse(text).replace('\n','')

        # 出力
        print( "\t".join((m, price)) )

    except RuntimeError as e:
        print("RuntimeError:" + e)

実行

$ ./mecab.py [excelファイル名]

2
2
11

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
2
2