顯示具有 stand library 標籤的文章。 顯示所有文章
顯示具有 stand library 標籤的文章。 顯示所有文章

2016年2月15日 星期一

Python standard library string

python standard libray string
提供了一些字串操作基本功能

str.translate(table[, deletechars])

translate可以依據table來轉換str
如果轉換的目標是None,則match的字元就會被刪除

>>> 'read this short text'.translate(None, 'aeiou')
'rd ths shrt txt'

參考網址
https://docs.python.org/2.7/library/string.html?highlight=translate#module-string

python standard library os

python standard library裡提供os這個module
可以進行os的一些基本操作
例如取得資料夾底下的檔案名

os.listdir(path)
列出路徑下,所有檔案名字

os.rename(src,dst)
將src檔名改成dst

os.getcwd( )
取得work directory 路徑

os.chdir(path)
改變work directory 路徑

參考網址
https://docs.python.org/2/library/os.html

2016年2月11日 星期四

python escape convert

要將字串轉成escape的型式
程式碼如下

def escape_covert(s):
    for (i, o) in ( ('&',  '&'),
                   ('>', '>'),
                   ('<', '&lt;'),
                   ('"', '&quot;'),
                   ):
        s = s.replace(i, o)
 
    return s
要注意 ('&',  '&amp;')要放第一個
否則其他escape charater
轉換完的&會被轉成'&amp
造成錯誤


但有更簡便的做法
就是import python的standard library cgi

import cgi

def escape_covert(s):
    return cgi.escape(s,quote=True)

參考網址
https://docs.python.org/2/library/cgi.html

2016年2月8日 星期一

Python Standard Library time

Python Standard Library裡有time module提供相關的功能



例如

想要暫停現在的動作可以使用sleep

time.sleep(1)


程式就會暫停1秒,再執行後面的動作

取得現在的時間可以用ctime

time.ctime( )

會回傳 星期 月份 日期 時:分:秒 年的型式,例如Mon Feb 08 23:24:26 2016

參考網站
https://docs.python.org/2/library/time.html

Python Standard Library webbrowser

Python Standard Library裡有webbrowser這個module

webbrowser提供簡單的function,來執行瀏覽器

例如
webbrowser.open(url, new=0, autoraise=True)

就會打開瀏覽器,瀏覽輸入url的網址的網頁

如果要指定特定瀏覽器來瀏覽
可以使用webbrowser.get來得到object
再使用這個object來呼叫open function


firefox = webbrowser.get('C:/Program Files (x86)/Mozilla Firefox/firefox.exe %s')
firefox.open("www.google.com")

這裡要注意的是傳入get function裡的路徑
與windows裡路徑使用' \ ' 不同
要使用unix-style的' / '才有辦法找到路徑

參考網站
https://docs.python.org/2/library/webbrowser.html