Last active
February 22, 2017 05:09
-
-
Save inakagawa/3e5ecb1d534d3b4c86d386873cfa4475 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import re | |
import pprint | |
def main(): | |
fh = get_fh() | |
data = read_from_fh(fh) | |
outdata = arrange_data(data) | |
for block in outdata: | |
for line in block: | |
print(line) | |
def get_fh(): | |
fh = None | |
if (len(sys.argv)>1): | |
# ファイルの存在確認、なければ終了 | |
datafile = sys.argv[1] | |
fh = open(datafile,mode="r",encoding="utf-8") | |
else: | |
fh = sys.stdin | |
return fh | |
def read_from_fh(fh): | |
data = [] | |
record = [] | |
with fh: | |
ln = fh.readlines() | |
for l in ln: | |
# l=l.rstrip() | |
l=l.strip() | |
if re.search('^$',l): | |
data.append(record) | |
record = [] | |
continue | |
record.append(l) | |
if len(record) > 0: | |
data.append(record) | |
return data | |
def arrange_data(data): | |
outdata = [] | |
for record in data: | |
firstline = record[0] | |
restlines = record[1:] | |
outrecord = [] | |
outrecord.append(firstline) | |
for item in restlines: | |
item = '\t'+item | |
outrecord.append(item) | |
outdata.append(outrecord) | |
return outdata | |
# pprint.PrettyPrinter(indent=2).pprint(sys.stdin.readlines()) | |
if __name__ == "__main__": | |
main() | |
# sys.exit() |
指定のファイル名で開く
fh=open(sys.argv[1],'r')
rstrip, strip
http://docs.python.jp/2/library/string.html#string.whitespace
無指定の場合は改行etcを除去
配列.append(val)
? 配列とリストの関係 etc
nullはNone
で表す
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
with/openの使い方
openの場合クローズを保証する
open→ファイルハンドルを返す
ファイルハンドルオブジェクトが、withに対応している
対応:enter(),exit() : 抜けたとき何をするか知っている
途中で例外が発生しても__exit__()は呼ばれる