2014年1月21日 星期二

difference between two strings in python

import difflib

s1 = "abcdefghijklmnop"
s2 = "abcdefghi"
s = difflib.SequenceMatcher(a=s1, b=s2)
for block in s.get_matching_blocks():
    print "match at a[%d] and b[%d] of length %d" % block

ref. http://stackoverflow.com/questions/1209800/difference-between-two-strings-in-python-php

2014年1月20日 星期一

Python sort dic by keys, values. sort list

Python dict sort keys, values

>>>numbers = {'first': 1, 'second': 2, 'third': 3, 'Fourth': 4}
>>> [key for key in sorted(numbers.keys())]
['Fourth', 'first', 'second', 'third']
>>> [value for value  in sorted(numbers.values())]
[1, 2, 3, 4]

#################################################

sort by key:
>>> dic={'hello': 1, 'aa': 2,'b':3}
>>> sorted(dic.items())
[('aa', 2), ('b', 3), ('hello', 1)]
------
>>> sorted(dic.items(),key=itemgetter(0))


sort by values:
>>> dic={'hello': 1, 'aa': 2,'b':3}
>>> sorted( dic.items(), key= lambda x:x[1] )    #dic.items()取出了x=[key,value],sort 是用x[1]
[('hello', 1), ('aa', 2), ('b', 3)]
>>> sorted(dic.items(),key=lambda x:x[1],reverse=True)
[('b', 3), ('aa', 2), ('hello', 1)]
------
>>> sorted(dic.items(),key=itemgetter(1))

##################################################

>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]

用 operator 函数来加快速度, 上面排序等价于:(itemgetter的用法)
>>> from operator import itemgetter, attrgetter
>>> sorted(students, key=itemgetter(2))

用 operator 函数进行多级排序
>>> sorted(students, key=itemgetter(1,2))  # sort by grade then by age
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

ref. http://www.pythoncentral.io/how-to-sort-python-dictionaries-by-key-or-value/
ref. http://obroll.com/how-to-sort-dictionary-by-keys-or-by-values-in-python/
ref. http://gaopenghigh.iteye.com/blog/1483864

Python 二維陣列

Python 二維陣列

可使用list=[list1,list2]的方式宣告
取值的方式為list[index1][index2]

ex.
>>> list2d=[[1,2],[3,4]]
>>> list2d
[[1, 2], [3, 4]]
>>> list2d[0][0]
1
>>> list2d[1][0]
3

2014年1月19日 星期日

git 基本使用

Linux git

$ git clone ssh://git@...
改完檔案,輸入"git status"檢查哪些檔案受到更新,untracked表示新加入的檔案尚未放在版本控制裏面; modified表示已經在版本控制中的檔案,且受到修改。
輸入"git pull"先讓server上的狀態和local的狀態進行同步。
輸入"git add filename1 filename2 ..." 其中filename是想要提交的檔案,不管是新增還是修改過的,都需要加進去。
輸入"git commit -m "comments"" 其中comments描述修改你修改了哪些東西。如果要輸入多行,在加入最後的雙引號"之前Enter即可:
git commit -m "this is
> a line
> with new lines
> maybe"
輸入"git push",同步至Server!

Generating SSH Keys

Generating SSH Keys

Step 1: Check for SSH keys
#############################################
cd ~/.ssh
ls
# Lists the files in your .ssh directory


Step 2: Generate a new SSH key
#############################################
ssh-keygen -t rsa -C "your_email@example.com"
# Creates a new ssh key, using the provided email as a label
# Generating public/private rsa key pair.
# Enter file in which to save the key (/c/Users/you/.ssh/id_rsa): [Press enter]
ssh-add id_rsa


Python 正規表示式

群組(grouping): 用小括號包起來
e.g.
import re
m = re.search('it is (fine (today))', 'it is fine today')
m.group(0)
m.group(1)
m.group(2)
#以上程式會依續印出完整字串、左起第一組小括號、第二組小括號


import re
f = open('/tmp/auth.log')
for i in f:
        regex = re.search(r'200\.[0-9]{1,3}\.[0-9]{1,3}\.([0-9]{1,3})', i)
        #加上小括號
        if regex:
                print regex.group(1)
                #加上小括號所出現的 index (從 1 開始算)
f.close()
-----------------------------------------------------------------------------------------------

字串切割重組
e.g.
import re
text = "hello123world456"
t="\t".join(re.split(r"\d+", text))
print t

-----------------------------------------------------------------------------------------------
\w = [a-zA-Z0-9_]
\s = [\t\n \r\f\v]
\d = [0-9] \w = [a-zA-Z0-9_]
\s = [\t\n \r\f\v]
\d = [0-9] 
大寫則有反義的用途,
例如 \D 是非數字,\W 代表非英數字、\S 代表非空白字元

------------------------------------------------------------------------------------------------


ref.
http://fannys23.pixnet.net/blog/post/15367167#comment-59040007

Python basic I/O

Python stdin
ex.
print 'Enter two numbers ...'
m=int(raw_input('Number 1:'))
n=int(raw_input('Number 2:'))

--------------------------------------------------------------------
Python 讀檔

# coding=UTF-8
filename = raw_input('檔名:')

f = open(filename, 'r')
b_str = f.read()
f.close()

print b_str.decode('utf-8') 
print b_str.decode('utf-8').encode('utf-8')


-------------------------------------------
import sys
file = open(sys.argv[1], 'r')
content = file.read()
print content
file.close()

 import sys
file = open(sys.argv[1], 'w')
file.write('test')
file.close()

-----------------------------------------
逐列:
import sys
file = open(sys.argv[1], 'r')
for line in file.readlines():
    print line
file.close()

簡化:
import sys
for line in open(sys.argv[1], 'r'):

    print line

Python 字串操作(截取/替換/查找/分割)

Python 字串操作


  • 字串截取 str = '12345678' print str[0:1] >> 1 # 輸出str位置0開始到位置1以前的字元
  • Python 替換字串使用 變數.replace("被替換的內容","替換後的內容"[,次數]),替換次數可以為空,即表示替換所有。要注意的是使用replace替換字串後僅為臨時變數,需重新賦值才能保存。
  • Python 查找字串使用 變數.find("要查找的內容"[,開始位置,結束位置]),開始位置和結束位置,表示要查找的範圍,為空則表示查找所有。查找到後會返回位置,位置從0開始算,如果每找到則返回-1。ex. str = 'a,hello' print str.find('hello') # 在字串str裡查找字串hello >> 2
  •  Python 分割字串使用 變數.split("分割標示符號"[分割次數]),分割次數表示分割最大次數,為空則分割所有。
    str = 'a,b,c,d' strlist = str.split(',') ,可用for x in strlist: print x 讀出
參考 http://fecbob.pixnet.net/blog/post/38077693


  • 去除換行,line=line.strip('\n')

Virtualenv for python

Virtualenv


  • 安裝:

   $ pip install virtualenv --user

  • 建立虛擬環境:

   $ mkdir virtual_dir
   $ virtualenv /path/to/virtual_dir/

  • 啟動虛擬環境:
   $ source /path/to/virtual_dir/bin/activate
  • 在虛擬環境下安裝套件:
   $ pip install package_name
  • 離開虛擬環境:
   $ deactivate