ファイルから特定の列を抽出する

実験データなどのファイルはmatrix状に整列されていることがほとんどです.特定の列(column)のデータを抽出したいというときには, UNIXコマンドではcat+awkなどを(awkだけ?)使うと綺麗にとりだすことができます.それをPythonで行うとどうなるかを実験します.


1: #! /usr/bin/env python
2: fp = open('data', "r")
3: weight = 0
4: num = 0
5: while 1:
6: s = fp.readline()
7: if not s:
8: break
9: # split()
10: #
11: # Returns the provided string with Python code
12: # as an array with tokens
13: t = s.split()
14: weight += float(t[0])
15: num += 1.0
16: print num
17: print weight, weight/num, num

13行目:

t = s.split()

にてsplit()関数を用いてファイルから読み込んだstring要素をarray要素に変換・分割してやります.


Reference
http://www.python.org/doc/2.3.5/lib/node109.html
http://www.harukaze.net/~haruka/map.html