2012年8月11日 星期六

with as

要打開文件,我習慣照書本教的
fobj = open(filename, 'r')

怕文件不存在,可能還得再加個捕捉錯誤

  1 
  2 
  3 
  4 
  5 
try:
    fobj = open(filename, 'r')
except IOError:
    pass
 
 
但有了with as 就方便多了,可以

  1 
  2 
with open(filename, 'r') as fobj:
    do something

為了讓class 也能使用,需添加二個函數__enter__和 __exit__
  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
class A:
    def __enter__(self):
        print 'in enter'
    def __exit__(self, e_t, e_v, t_b):
        print 'in exit'

with A() as a:
    print 'in with'


in enter
in with
in exit


使用模組contextlib,便不用構造__enter__和 __exit__

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
>>> from contextlib import contextmanager
>>> from __future__ import with_statement
>>> @contextmanager
... def context():
...     print 'entering the zone'
...     try:
...         yield
...     except Exception, e:
...         print 'with an error %s'%e
...         raise e
...     else:
...         print 'with no error'
...
>>> with context():
...     print '----in context call------'
...
entering the zone
----in context call------
with no error
官方範例
  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
from contextlib import contextmanager

@contextmanager
def tag(name):
    print "<%s>" % name
    yield
    print "</%s>" % name

>>> with tag("h1"):
...    print "foo"
...
<h1>
foo
</h1>

還有一個closing可在抓網頁資料時使用


  1 
  2 
  3 
  4 
  5 
  6 
from contextlib import closing
import urllib

with closing(urllib.urlopen('http://www.python.org')) as page:
    for line in page:
        print line



LIST的妙用

彼得.狼的獸窩   看到一遍文章覺得蠻有趣的!
 Java & Python 程式碼疊疊樂之二

內容主要比較 python&java寫輸入一分數判定等級ABCDE那種

這種東西常見的寫法大部分都是:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Filename: gradingRobotOne.py

grade = raw_input("請輸入分數: ") #利用 raw_input 的函式取得鍵盤輸入
score = int(grade) #從 raw_input 取得的字串類型 (String) 資料,轉換為 int 的類型
print "====================="
print "您輸入的分數為:", score

gradeLevel = "未判定!" #預設成績等級為「未判定!」
#利用判斷式把輸入的成績分等級
if score > 100 or score < 0:
print "分數應該介於 0 到 100 之間!"
elif score <= 100 and score >= 90:
gradeLevel = "A"
elif score <= 89 and score >= 80:
gradeLevel = "B"
elif score <= 79 and score >=70:
gradeLevel = "C"
elif score <= 69 and score >=60:
gradeLevel = "D"
else:
gradeLevel = "F"

print "成績評定為:", gradeLevel #印出評定結果



那有趣的是,我看最後面有一個回文提供的寫法,蠻有智慧的!

Grade = ["E","D","C","B","A"];
Score = int(raw_input());
print Grade[int((Score-51)/10)]; 

直接利用LIST的特性,判定成績,讓代碼大為減少!!!
 


 

擲骰子遊戲

模擬 烤香腸路邊攤 擲骰子遊戲
規則:由雙方各擲一次骰子比大小,一次擲四顆,其中二顆需要同點數,計算另二顆相異點數總和,如四顆同點數,則為最大稱為「一色」,三點則為最小。

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
 31 
 32 
 33 
 34 
 35 
 36 
 37 
 38 
 39 
 40 
 41 
 42 
 43 
 44 
 45 
 46 
 47 
 48 
 49 
 50 
 51 
 52 
 53 
 54 
 55 
 56 
 57 
 58 
 59 
 60 
# -*- coding: UTF-8 -*-
import random

def score_count(point):
    score = 0
    check = len([i for i in set(point)])
    if check == 1:
        score = 19
    elif check == 2:
        if point.count(max(point)) == 2:
            score = max(point) * 2
        else:
            score = 0
    elif check == 3:
        for i in point:
            if point.count(i) == 1:
                score += i
    else:
        score = 0
    return score

def rand_dice(name):
    i = 1
    score = 0
    while not score:
        point = [random.choice(dice) for c in range(4)]
        score = -1
        score = score_count(point)
        print "%s第 %s 次,擲出:" % (name, i), point
        if score == 19:
            print "一色"
        else:
            print score, "點"
        i += 1
    return score

print "***擲骰子遊戲***"
win, lose = 0, 0
dice = [i for i in range(1,7)]

while 1:
    c_score = rand_dice('電腦')
    play = raw_input('請按Enter擲骰子')
    u_score = rand_dice('玩家')
    if c_score > u_score:
        print '你輸了!'
        lose += 1
    elif c_score < u_score:
        print '你贏了!'
        win += 1
    else:
        print '平手!'
    print '目前戰績%s勝%s負' % (win, lose)
    play = raw_input('是否繼續(y/n)?')
    if play in ('n', 'N'):
        print '目前戰績%s勝%s負' % (win, lose)
        print 'Good Bye!'
        break
    else:
        pass