16
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

prettytableを使って簡単な表の作成

Last updated at Posted at 2015-10-21

prettyprintで表の作成

詳細はこちら:https://pypi.python.org/pypi/PrettyTable
下記のものをpipでインストールしました。
listの各要素の長さがバラバラで、出力してみても見にくい時とかに便利です。
今回のコード:https://github.com/KodairaTomonori/Qiita/blob/master/module/prettyprint/make_table.py

pip.
$ pip search prettytable
prettytable-extras     - An extension to the excellent prettytable Python library

実際に作ってみる

今回は形態素解析をしてくれるmecabをつかって説明していきます。
mecabは、文を入れると、形態素解析結果を文字列として返してくれます。
こちらも簡単にpipでインストールできます。

mecab_test.
$ python
Python 3.5.0
>>> import MeCab
>>> MeCab.Tagger().parse('体は剣で出来ている')
'体\t名詞,一般,*,*,*,*,体,カラダ,カラダ\nは\t助詞,係助詞,*,*,*,*,は,ハ,ワ\n剣\t名詞,一般,*,*,*,*,剣,ケン,ケン\nで\t助詞,格助詞,一般,*,*,*,で,デ,デ\n出来\t動詞,自立,*,*,一段,連用形,出来る,デキ,デキ\nて\t助詞,接続助詞,*,*,*,*,て,テ,テ\nいる\t動詞,非自立,*,*,一段,基本形,いる,イル,イル\nEOS\n'
>>> print(MeCab.Tagger().parse('体は剣で出来ている') )
体	名詞,一般,*,*,*,*,体,カラダ,カラダ
は	助詞,係助詞,*,*,*,*,は,ハ,ワ
剣	名詞,一般,*,*,*,*,剣,ケン,ケン
で	助詞,格助詞,一般,*,*,*,で,デ,デ
出来	動詞,自立,*,*,一段,連用形,出来る,デキ,デキ
て	助詞,接続助詞,*,*,*,*,て,テ,テ
いる	動詞,非自立,*,*,一段,基本形,いる,イル,イル
EOS

こんな感じで出力されますが、ただプリントしただけでは、何か後ろの方が揃ってなくて見にくい
なので、prettytableをつかってこれを簡単に見やすくしたいと思います。

make_prettytable.py
import MeCab
import prettytable

def make_prettytable(others, header=[]):
    if not header: header = range(len(list(others)[0]) )
    if len(header) != len(others[0]):
        print('incorrect length!')
        return 
    table = prettytable.PrettyTable(header)
    for other in others: table.add_row(other)
    return table

def make_mecab_info_table(sentence, output_info=[], \
        mecab_parser=MeCab.Tagger.parse):
    others = list(map(lambda x: x.split(','), \
        mecab_parser(sentence).replace('\t', ',').split('\n') ) )[:-2]
    return make_prettytable(others, output_info)


if __name__ == '__main__':
    mecab_output = '表層形,品詞,品詞細分類1,品詞細分類2,品詞細分類3,活用形,活用型,原形,読み,発音'
    parser = MeCab.Tagger().parse
    header = mecab_output.split(',')
    print(make_mecab_info_table(input(), header, parser) )

出力例

スクリーンショット 2015-10-21 21.29.05.png

解説

こんな感じで見やすくなりました。
make_prettytableは最初の引数(others)には中身を、次の引数(header)には、上段の情報を入れています。
headerは引数を受けとんなかった場合に、rangeで番号を振ってあげてます。
others[[1,2,...], [2,3,...]...]的なリストを入れてあげればいいです。
prettytable.PrettyTableで上段(header)を入れて表の元を作ります。
次のfor文でothersを回して.add_rowで一行づつ追加して行っています。
あとは、printするだけで簡単に表が見れます。

make_mecab_info_tableは、普通に文字を処理しているだけです。

listの要素の長さがバラバラの時、出力して確認しようとしてもなんか見にくいのでそんな時に便利です。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?