言語処理100本ノックやった 10-13 #python
#!/usr/bin/python # -*- coding: utf-8 -*-
今日から第2章
ここまでは「準備運動」
第2章では 'hightemp.txt' というファイルをごにょごにょする。
ファイルを扱うのは
fhand = open('filename.txt') for line in fhand: いろいろ fhand.close()
が基本?(Coursera で習ったのはそんな感じだった)
#10 行数カウント
fhand = open('hightemp.txt') cnt = 0 for line in fhand: cnt += 1 print 'line count:', cnt #line count: 24 fhand.close()
ラインごとにカウンターを増やす、シンプル
#11 タブをスペースに置換
import re fhand = open('hightemp.txt') spaced = open('hightemp_spaced.txt', 'w') for line in fhand: line = line.strip() line = re.sub('\t', ' ', line) # 3の中の1を2に置換したもの spaced.write(line + '\n') fhand.close() spaced.close()
7.2. re — 正規表現操作 — Python 2.6ja2 documentation
置換するところは冷静に
line = line.replace('\t', ' ')
でおk
#12 1列目をcol1.txtに,2列目をcol2.txtに保存
fhand = open('hightemp.txt') f0 = open('col1.txt', 'w') f1 = open('col2.txt', 'w') for line in fhand: line = line.strip().split() f0.write(line[0] + '\n') f1.write(line[1] + '\n') fhand.close() f0.close() f1.close()
特にコメントなし
#13 col1.txtとcol2.txtをマージ
fhand0 = open('col1.txt') fhand1 = open('col2.txt') f = open('merged.txt', 'w') prefec, place = [], [] for line in fhand0: line = line.strip() prefec.append(line) for line in fhand1: line = line.strip() place.append(line) for i in xrange(len(prefec)): f.write(prefec[i] + '\t' + place[i] + '\n') fhand0.close() fhand1.close()
1列目のリストを作って、2列目のリストを作って、1行ずつ並べながら出力
もっとかっこいいやり方ありそう。
#13 改良版
fhand0 = open('col1.txt') fhand1 = open('col2.txt') f = open('merged.txt', 'w') prefec = fhand0.readlines() place = fhand1.readlines() for pre, pla in zip(prefec, place): f.write(pre.strip() + '\t' + pla.strip() + '\n') fhand0.close() fhand1.close() f.close()
リストを自分で作らなくても .readlines() すればリストが得られることが判明
zip も覚えた
forループで便利な zip, enumerate関数 » Python Snippets
2. 組み込み関数 — Python 2.7ja1 documentation
おわり
それっぽいファイルは出力できたのでとりあえず良さそう。