2016年9月24日土曜日

開発環境

Exercises for Programmers: 57 Challenges to Develop Your Coding Skills (Brian P. Hogan 著、Pragmatic Bookshelf)のChapter 8(Working with Files)、42(Parsing a Data File)を取り組んでみる。

42(Parsing a Data File)

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

filename = 'sample.csv'

header = ['Last', 'First', 'Salary']
data = []
cols = list(map(len, header))
with open(filename) as f:
    for line in f:
        t = list(map(lambda x: x.strip(), line.split(',')))
        cols0 = list(map(len, t))
        cols = list(map(lambda t: max(t), zip(cols, cols0)))
        data.append((t[0], t[1], t[2]))

cols = list(map(lambda x: x + 1, cols))
fmt1 = '{{0:{0}}}{{1:{1}}}{{2:{2}}}'.format(*cols)
fmt2 = '{{0:{0}}}{{1:{1}}}{{2:>{2}}}'.format(*cols)

data.sort(key=lambda x: -int(x[2]))
print(fmt1.format(*header))
print('-' * sum(cols))
for a, b, c in data:
    print(fmt2.format(a, b, c))

print('csv module')
import csv

with open(filename) as f:
    reader = csv.DictReader(f, fieldnames=header)
    data = [d for d in reader]

cols = list(map(len, header))
for d in data:
    v = d.values()
    cols0 = list(map(len, [d['Last'], d['First'], d['Salary']]))
    cols = list(map(lambda t: max(t), zip(cols, cols0)))

cols = list(map(lambda x: x + 1, cols))
fmt1 = '{{Last:{0}}}{{First:{1}}}{{Salary:{2}}}'.format(*cols)
fmt2 = '{{Last:{0}}}{{First:{1}}}{{Salary:>{2}}}'.format(*cols)
print(fmt1.format(**dict(zip(header, header))))
print('-' * sum(cols))
for d in data:
    print(fmt2.format(**d))

入出力結果(Terminal, IPython)

$ ./sample42.py
Last     First    Salary 
-------------------------
Xilong   Fong       65000
Johnson  Jim        56500
Ling     Mai        55900
Zarnecki Sabrina    51500
Jones    Aaron      46000
Jones    Chris      34500
Swift    Geoffrey   14200
csv module
Last     First    Salary 
-------------------------
Ling     Mai        55900
Johnson  Jim        56500
Jones    Aaron      46000
Jones    Chris      34500
Swift    Geoffrey   14200
Xilong   Fong       65000
Zarnecki Sabrina    51500
$

0 コメント:

コメントを投稿