【轉碼 / 編碼】

1. Linux 上預設環境是 UTF-8、Windows 是 Big5,
因此要印資料或資料中存有中文時,
檔案開頭要指定適當的編碼:

UTF-8
#-*- coding: utf-8 -*-

Big5
#-*- coding: big5 -*-
#-*- coding: cp950 -*-


 

 

2. 若以Big5儲存,想要轉碼為UTF-8時,
必須先 decode 為 unicode 字串,再 encode 為 UTF-8

abc = '測試'
abc.decode('big5').encode('utf-8')



3. 檔案試轉編碼
#-*- coding: cp950 -*-
import os
os.chdir(r"C:\Documents and Settings\username\桌面")
myfrom = open('123.txt')
myto = open('dest.txt', 'w')
txt = myfrom.read()
myto.write(txt.decode('big5').encode('utf8'))
myfrom.close()
myto.close()
os.system("pause")



4. 取得資料夾下的檔名,使用萬用字元 (wildcard, '*')

import glob
glob.glob('.*')         #檔案列表以 list 回傳
for i in glob.glob('*'):     #以 for 迴圈取得檔案列表後逐個列出
    print i




【Mapping Type】

1. 過去的陣列必須要用索引值取得陣列內的值,
Dictionaries 可以給予每個陣列元素一個取用時的名稱 (key),
使得取用時,能以有意義的名稱取用;
但在 dict 中,不像 list 的陣列內容是有序的,
dict 是以 hash 的方式存放,因此內容不保證其順序,
也因此不能以 a[1] 這類方式取用

a = {'name':'fannys23', 'email':'test@fannys23.com', 'money':200}
a['money']
a['address'] = 'Kaohsiung City'



2. dict 的 key 可以用 string, tuple, integer
例如:
a = {'name':'fannys23', 'email':'test@fannys23.com', 209: 'Fanny'}
a[209]



3. php / C / C++ / Perl...等等屬於 static strong type 的語言,
因此可以做字串與數值的相加等動作,會自動協助型別轉換,
python 是強型別的語言 (dynamic strong type),
不允許曖昧的型別指定,
因此 a['addr'] = 'test' 這樣的寫法會有錯誤



4. dict 和 list 可以使用 del 刪除當中的部分元素
a = [1,2,3,4]
del a[1:3]
b = {'name':'fannys23', 'email':'test@fannys23.com', 'money':200}
del b['name']



5. 排序 dict 中的內容:

#將 dict 內容依 key 值排序
b = {'name':'fannys23', 'email':'test@fannys23.com', 'money':200}
sorted(b.keys())

#搭配 for
b = {'name':'fannys23', 'email':'test@fannys23.com', 'money':200}
for i in sorted(b.keys()):
    print b[i]



【函式 (functions) 的撰寫】

1. function 一定會有回傳值,若未指定 return 會自動回傳一個空值 (none)
def 函式名稱(參數):
     "documentation string"   #說明文件
    程式內容
    return 回傳值        #沒寫這行的話,會 return none



2. 對 list 與 dict,python 會以傳址呼叫 (call by reference)

#使用 append 可在 list 後加入新元素
def test(name):
    name.append(100)
mylist = [1,2,3]
test(mylist)

#若想要傳值呼叫,要先複製一份 list
def test(name):
    name.append(100)
    print name

mylist = [1,2,3]

test(mylist[:])        #複製一個 list,不會影響最原始的 mylist
mylist            #mylist 仍是原本內容



3. python 中因為可以直接傳入多種形式的變數,
例如可同時傳入 string、list 等內容,所以沒有多載 (overloading)



【邏輯】

1. X is Y: 當兩個物件指向同一物件,則回傳 true;
若指向記憶體位址中不同物件,則回傳 false

x = [1,2,3]
y = x[:]
x is y        #指向不同物件,傳回 false
y = x
x is y        #指向同一物件,傳回 true



2. 類似 C language 中的 (X>Y):A?B

x = 300
y = 100
x = 'yes' if x > y else 'no'
#僅適用於簡單運算



【迴圈】

1. 在迴圈中直接將 list 元素值改變,
若未指定將新的 list 存至何處,
則迴圈結束後,新的 list 就消失

li = [3, 6, 2, 7]
[elem*2 for elem in li]



2. 迴圈加上 multiple assign 的概念:
li = [('a', 1), ('b', 2), ('c', 7)]
[n * 3 for (x, n) in li]



3. 再加上 if 判斷式作為 filter

#取出偶數將之平方
li = [1,2,3,4,5,6]
[ n**2 for n in li if n%2==0 ]



【其他】

1. 在 python 中也有類似 C lanugage 中 printf 的表現方式
"%s hello" % "test"
"%s %d hello" % ("wang",209)
"%s %s hello" % ("test1","test2")     #兩個以上的值要加上小括號變成 tuple


2. join()可以將 list 的元素間加入分隔符號

test = "it is fine today \n"
"".join(test.split())
#用split()去除空白、分行符號、tab 等元素,再由 join 加上空字串,表示將原始字串的空白消除乾淨




【實作練習:登入討論區並取得討論區資料】

import urllib, urllib2, cookielib
cj = cookielib.CookieJar()
agent = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
params = urllib.urlencode({'uname':'username','pass':'userpasswd','xoops_redirect':'/pki/','op':'login'})
f = urllib.urlopen("http://pki.nknu.edu.tw", params)
agent.open('http://pki.nknu.edu.tw/pki/user.php', params)
web = agent.open('http://pki.nknu.edu.tw/pki/modules/newbb/')
print web.read()

 

 

 

 

 

 

arrow
arrow
    全站熱搜

    小攻城師 發表在 痞客邦 留言(1) 人氣()