Python.use(better) #body: step08 -- def body(file, start=1, end=None):

記事一覧 Python.use(better)《Python3.1》

body: step08 -- def body(file, start=1, end=None):

《著》森こねこ、小粒ちゃん+∞《監修》小泉ひよ子とタマゴ倶楽部
第0版♪2001/03/02 ● 第1版♪2003/05/25 ● 第2版♪2004/06/01 ● 第3版♪2009/02/28

課題を作成する過程を通して「ファイル操作」の理解を深めます。
※ Python1.5 で作成した例題を、Python3.1 で再構成しました。

事例:コードの解説

    def body(file, start=1, end=None):
        with open(file) as s:
            s = s.readlines()
            format = "%%%dd: %%s"%len("%d"%len(s))
            s = s[start-1:end]
            for i,e in enumerate(s):
                n = start+i
                print(format%(n,e),end="")

    ## ----------------------------------------
    local = locals()
    ex_body3(local, "temp")

前述したコード》をもとに、テストファイルを生成する部分を、関数 ex_body として抽出(リファクタリング)します。

■ #1: スライス
            s = s[start-1:end]

start-1 から end の手前までの要素を列挙した、部分リスト s が得られます。

事例:モジュールを起動する

■ 全項目を確認する

全ステップの「項目」を確認するには、関数 do を利用します。

$ python -i my_range.py
>>> do()
0: step00 -- open(file,"w")
1: step01 -- s.write(...)
2: step02 -- open(file,"r")
3: step03 -- for i,e in enumerate(f):
4: step04x -- f.readlines()
5: step05 -- print(format%(n,e),end="")
6: step06 -- def body(file):
7: step07 -- def body(file, end=None):
8: step08 -- def body(file, start=1, end=None):
9: step09 -- print("".join(s),end="")
>>>
■ 各項目を実行する

各ステップの「動作」を確認するには、関数 do に実引数を指定します。

>>> do(8)
>>> # -------------------------------------------------- step08
>>> body('temp')
 1: A - 65
 2: B - 66
 3: C - 67
 4: D - 68
 5: E - 69
 6: F - 70
 7: G - 71
 8: H - 72
 9: I - 73
10: J - 74
>>> body('temp',end=3)
 1: A - 65
 2: B - 66
 3: C - 67
>>> body('temp',start=8)
 8: H - 72
 9: I - 73
10: J - 74
>>> body('temp',start=3,end=5)
 3: C - 67
 4: D - 68
 5: E - 69
>>> body('temp',end=8,start=6)
 6: F - 70
 7: G - 71
 8: H - 72
>>>

新たにファイル 'temp' を作成するとともに、行番号に続いて各行を出力します。

  • 先頭行から 3 行目までを出力します。
  • 8 行目から末尾行までを出力します。
  • 3 行目から 5 行目までを出力します。
  • 6 行目から 8 行目までを出力します。

《余録》テストケース

def ex_body3(local, n):
    ex_body2(local, n)

    source = '''
body({0!r},start=8)
body({0!r},start=3,end=5)
body({0!r},end=8,start=6)
'''.split("\n")

    for e in source[1:-1]:
        print_(e.format(n), local)

》こちらに移動中です《
TOP


関連記事

Last updated♪2009/11/13