開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの無料機能制限版、light版)
- Script言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のV部(モジュール)まとめ演習1(簡単なモジュールファイルのインポート)を解いてみる。
その他参考書籍
1.
コード(TextWrangler)
sample.py
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- def count_lines(name): return len(open(name).readlines()) def count_chars(name): return len(open(name).read()) def test(): name = input("ファイル名を入力: ") return "行数:{0} 文字数:{1}".format( count_lines(name), count_chars(name)) # test関数でのopen関数の呼び出しを2回ではなく1回で済むように修正 def count_lines1(file): file.seek(0) return len(file.readlines()) def count_chars1(file): file.seek(0) return len(file.read()) def test1(): name = input("ファイル名を入力: ") file = open(name) return "行数:{0} 文字数:{1}".format( count_lines1(file), count_chars1(file))
入出力結果(Terminal)
$ python Python 3.3.0 (default, Sep 29 2012, 08:16:08) [GCC 4.2.1 Compatible Apple Clang 3.1 (tags/Apple/clang-318.0.58)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from sample import * >>> count_lines('sample.py') 28 >>> count_chars('sample.py') 625 >>> test() ファイル名を入力: sample.py '行数:28 文字数:625' >>> test1() ファイル名を入力: sample.py '行数:28 文字数:625' >>> quit() $
0 コメント:
コメントを投稿