2016年12月22日 星期四

[sublime]安裝中遇到的問題

anaconda的安裝
anaconda使用後會出現一些白框框住程式碼
How to fix:
Sublime > Preferences >Package >Anaconda >Settings User
會出現一個空白文件,加上{"anaconda_linting":false}即可

2016年12月20日 星期二

[Python]1.9.2 自定義函式

def 函式名稱(參數1, 參數2........):
      若干運算(敘述)
       return 回傳值1, 回傳值2......

 可以沒有回傳值

 def power(base,exp):
       return base**exp

函式的呼叫
power(2,3)
power(exp=3,base=2)

遞迴
如果我們今天有一個清單

lst = [1,2,[1,2,3],2,4,5,[23,12],[12,23,34,67]]

def print_list(lst):
 for item in lst:
  if isinstance(item,list):
   print_list(item)
  else:
   print item,

#isinstance(item,型態)這個方法就是問
#請問item是這個型態嗎?

#這邊要注意,運用遞回的方法把每一層的list剝開
print_list(lst)
執行結果 >>>1 2 1 2 3 2 4 5 23 12 12 23 34 67


參數的預設值
def add(a,b=1):
      return a+b

注意:帶有預設值的參數都需擺在沒有預設值的後面,
            位置呼叫時無法指定哪一些參數用預設值


2016年12月19日 星期一

[Python]1.9.1 內建函式

1.9.1 內建函式
內建函式的paper

工廠函式:專門負責型態或是製造資料
for example:
int('99') -------------99
float('1.73')----------1.73
bool('')---------------False
str(20)----------------'20'
list((1,2,3))----------[1,2,3]
list(set([1,1,2,2])----[1,2]























全部或任何
“對於所有”(for all) “存在一個” (exist) 在邏輯上是個很重要的概念
member = {'jack':90,'jerry':85,'jimmy':43,'Wang':9,'LI':23}
a = {}
for name,grade in member.items():
    
    if grade>60:
        a[name]=True
    else:
        a[name]=False
            
if all(a.values()):
    print "Everyone pass the test"
else:
    print "someone did not pass the test"
    for name,ch in a.items():
        if ch == False:
            print name
#這裡要注意的是dic資料的取用,用for 方法
#a.items()
#a.keys()
#a.values()




執行結果





















分析
all():會對list裡面的所有元素進行檢查,若全部元素為真,傳回True,否則傳回False
另一個函數any()則是只要一個人為真,就傳回真了

最大與最小
max(lst)
min(lst)

產生連續的整數
range(10)-----------[0,1,2,3,4,5,6,7,8,9]
range(2,7)----------[2,3,4,5,6]
range(2,13,3)-------[2,5,8,11]

群集的長度
>>>lst = [1,2,3,4,5]
>>>print len(lst)
>>>5
>>>dic = {1:2,2:2,3:2}
>>>print len(dic)
>>>5







[Python]1.8 例外

動態語言中,除了語法錯誤造成的Syntax Error以外,幾乎所有的錯誤都來自執行期的錯誤.像是TypeError或是NameError等等.當錯誤發生時,Python會產生Traceback,方便檢視錯誤的來源. 但是在開發時,重要的不是辨識每一個錯誤而是排除掉一些不是錯誤的錯誤,例外. 舉個例子:
#有個檔案test_file.txt

3 4
1 3

20 19
%%%
88 7
1 2 3 
0
#使用try except 敘述來避開中間%%%的例外
f = open('/Users/lijack/Desktop/test_file.txt')
for lines in f:
    try:
        a , b = lines.strip().split()
        print "{:>2} + {:>2} ={:>3}".format(a,b,int(a)+int(b))
        
    except:
        pass
#python 不允許有suite是空白的
    
    
f.close


#strip()函數會移除字串頭尾指定的符號
string = "     12342342314213     "
print string.strip()

string1 = "8888888dfasfsdfsdafasdf888888"
print string1.strip('8')

#split函數:用特定字符切割字串
string2 = "hello world jack"
a,b,c = string2.split()
print a
print b
print c



















分析:如果沒有用try - except 敘述時,有幾行( %%%, 1 2 3)沒有符合兩個數字的形式,便會出現ValueError.如果用if -else 敘述時,會出現很多種複雜的狀況.但其實我們並不需要去處理跟我們需要不相關的事.

執行:我們先執行try的程式碼,當發生錯誤時,立刻停止try,進入except 執行suite 裡的程式碼(ex: pass),在這題等於我們略過了所有不符合規格的行.

2016年12月13日 星期二

[Django] 1.7.3 讀檔與寫入檔案

資料檔的讀寫是python 的基本功能之一

開啟檔案:使用open函數

fp = open('test_file.txt','r')
a = fp.read()
b = fp.readline()
c = fp.readlines()
fp.close()
其中,test_file的欄位可填入絕對路徑,但是請注意
windows: fp = open('C:\\Users\\jack\\Desktop\\test_file.txt')
mac : fp = open('/Users/Documents/test_file.txt')
因為windows的路徑的斜線是\,會造成跳脫字元,所以要輸入兩個\
而mac沒有這個困擾

r:讀檔 w:寫入 a:附加

讀取檔案的方法有三種:read(), readline(), readlines()
      read() : 一口氣讀完
 readline():一次只讀一行文字檔,傳回一個字串
readlines():把每一行拆開放在不同的字串變數,最後彙整成一個串列




f = open ('C:\\Users\\jack\\Desktop\\MP21602\\zop.txt','r')

print (f.read())

#f = open ('C:\\Users\\jack\\Desktop\\MP21602\\zop.txt','r')
print (f.readline())
print (f.readline())

f = open ('C:\\Users\\jack\\Desktop\\MP21602\\zop.txt','r')
print (f.readlines())
read() 會顯示全部內容
readline() 照理說會顯示
 >>>
Beautiful is better than ugly

 Explicit is better than implicit
>>>

 因為純文字格式每行後面都有個換行符號\n ,加上本身print也有一個換行
有兩種解決方法
(1) 用strip()清除字串頭尾非必要字元
(2) print      ,end=""

使用with敘述可以讓程式更簡潔

with open('C:\\Users\\jack\\Desktop\\MP21602\\zop.txt','r') as f:
     for line in f:
         print line

上述程式把要讀取的檔案名稱寫在程式碼並不是個很好的方式,通常會把要操作的文字對象已執行參數的方式輸入 程式命令列函數可以用sys.argv取得

import sys

if len(sys.argv)<2:
    print("How to use: python 8-2.py class")
    exit(1)

std_data = dict()

with open(sys.argv[1],encoding='utf-8') as fp:
    alldata = fp.readlines()

for line in alldata:
    no,name = line.rstrip('\n').split(',')
    std_data[no] = name

print (std_data)

<\pre>


[Django]1.7.2

break and continue

如果while的條件總是成立,我們稱其為無窮迴圈.
使用時機:當我們的程式需要等待使用者的一些要求時

while True:
print “never stop”

而break 跟 continue 則可以強制介入迴圈

n = 5

count = 1

while True:

print "just print {} times".format(count)

if count == n:



break

count+=1

continue 的用法

n = 1

while n<=10:

if n==5:

n+=1

continue

print n

n+=1

for 迴圈

lst = [1,2,3]
for num in lst:
print num

for item in lst:
suite
將lst中的元素一個個取出,每取出一個便將他賦值(代入)
並且執行一次suite

for 可以對清單 元組 字典 字串 進行迭代

使用時機
for :當重複的次數可以被計算時
while:當條件清楚時



comprehension

lst = [1,2,3,4,5]
lst_eq = [n**2 for n in lst]
lst_eq1=[n**2 for n in lst if n%2==0]

>>>lst_eq
[1,4,9,16,25]
>>>lst_eq1
[4,16]

scores = [88,90,100,65,78]
score_dic = {student_id :score for student_id,score in enumerate(scores)}

>>>score_dic
{0: 88, 1: 90, 2: 100, 3: 65, 4: 78}

enumerate是一個函數,當它與for 搭配時,他會同時把索引值與元素取出

1.7 輸入與輸出

print函式
1.任何基本資料都可以用print輸出
2.print 1,———不斷行列印 加逗號

input函式
guess = 6
while True:
guess_number = int(input('please enter a num \n'))
if guess_number == guess:
print "right"
break
else:
print “wrong"
注意:任何輸入都會被當成字串,需要轉換



[python] selenium 爬蟲安裝指南

http://www.kenst.com/2015/03/installing-chromedriver-on-mac-osx/

1.First, you need to download chromedriver
2.create a path for chromedriver

sudo nano /etc/paths

add path of chromedriver
ex: /Users/jackli/Documents/webdriver

To check:
echo $PATH

3.move chromedriver to your own path