2013年11月18日月曜日

開発環境

初めてのコンピュータサイエンス(Jennifer CampbellPaul GriesJason MontojoGreg Wilson(著)長尾 高弘(翻訳))の8章(ファイル処理)、8.8(練習問題)、3.を解いてみる。

8.8(練習問題)、3.

コード(BBEdit)

sample.py

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

fields = (((4, int), (2, int), (2, int)),
          ((2, int), (2, int), (2, int)),
          ((2, int), (2, int), (2, int)),
          ((6, float), (6, float), (6, float)))
def readWeatherData(r, fields):
    result = []
    for line in r:
        start = 0
        record = []
        for field in fields:
            group = []
            for width, target_type in field:
                text = line[start:start+width]
                value = target_type(text)
                group.append(value)
                start += width
            record.append(tuple(group))
        result.append(tuple(record))
    return result

def readWeatherDataWrap(r):
    fields = (((0, int), (4, int), (6, int)),
              ((8, int), (10, int), (12, int)),
              ((14, int), (16, int), (18, int)),
              ((20, float), (26, float), (32, float)))
    new_fields = []
    new_field = []
    flag1 = True
    temp_i = 0
    temp_target_type = ""
    for field in fields:
        flag2 = True
        for i, target_type in field:
            if flag1:
                flag1 = False
                flag2 = False
            else:
                new_field.append((i - temp_i, temp_target_type))
                if flag2:
                    new_fields.append(tuple(new_field))
                    new_field = []
                    flag2 = False
            temp_i = i
            temp_target_type = target_type
    else:
        for line in r:
            new_field.append((len(line) - temp_i, temp_target_type))
            new_fields.append(tuple(new_field))
            break
        r.seek(0)
    new_fields = tuple(new_fields)
    return readWeatherData(r, new_fields)

with open('weather.txt') as f:
    records = readWeatherData(f, fields)
    for record in records:
        print(record)
    print("ラッパ関数")
    f.seek(0)
    records = readWeatherDataWrap(f)
    for record in records:
        print(record)

入出力結果(Terminal)

$ cat weather.txt
20070503241737385605100.00121.3016.370
20070503241737385605100.00121.3016.370
$ ./sample.py
((2007, 5, 3), (24, 17, 37), (38, 56, 5), (100.0, 121.3, 16.37))
((2007, 5, 3), (24, 17, 37), (38, 56, 5), (100.0, 121.3, 16.37))
ラッパ関数
((2007, 5, 3), (24, 17, 37), (38, 56, 5), (100.0, 121.3, 16.37))
((2007, 5, 3), (24, 17, 37), (38, 56, 5), (100.0, 121.3, 16.37))
$

0 コメント:

コメントを投稿