顯示具有 Python 標籤的文章。 顯示所有文章
顯示具有 Python 標籤的文章。 顯示所有文章

2013年5月22日 星期三

[Python] list pip installed packages - 列出pip已安裝的套件

List all installed packages - 列出所有已安裝的套件

$ pip freeze

Check specify package version - 查看某套件版本

$ pip freeze | grep Django

2013年3月11日 星期一

[Sublime Text] 解決編譯Python時無法找到相關模組 No module named xxx when build Python

OS: Mac OSX 10.8.2
Sublime Text Build: 2220

當用Cmd+B Build Python時, 會發現即使已經安裝的模組還是無法Build

ImportError: No module named xxx

所以藉由加入Module路徑到Sublime Text設定檔的Python.sublime-build裡來解決

編輯Python.sublime-build
subl ~/Library/Application\ Support/Sublime\ Text\ 2/Packages/Python/Python.sublime-build

加入PYTHONPATH到設定檔中即可

2011年3月25日 星期五

[Python] Install pip on Windows

1. 下載並安裝easy_install

Easy Install: http://pypi.python.org/pypi/setuptools#using-setuptools-and-easyinstall

2. 透過easy_install直接安裝pip

$ easy_install pip

3. 如果安裝不順利可以透過下載pip的壓縮檔來安裝

Pip: http://pypi.python.org/pypi/pip

4. 用cmd到pip的資料夾下, 安裝pip

python setup.py install

5. 將Python的路徑加至環境變數的PATH中 (C:\Python2x\Scripts)

成功! 之後就可以用pip install來安裝Package
$ pip install *package*

[Django] Detect Django Version - 取得Django版本

$ pip freeze | grep 'Django'

Django==1.5.1

Or

$ python

Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.VERSION
(1, 3, 0, 'final', 0)

Or

python -c "import django; print(django.get_version())"

2011年3月16日 星期三

[Python] 將Run Python的快捷鍵新增至Komodo的Toolbox

在Toolbox新增一個Command

Command填即可
%(python) %F

可以在Key Binding裡設定你要的快捷鍵

2011年1月25日 星期二

[Python] PythonBee - 冠軍賽- 用嘴巴講出一套好程式



(不負責任翻譯XD)


This is from the final round where our last two contestants competed for a Kindle.
這影片是最後決戰的兩位參賽者

Contestants were not allowed to see their code or have it read back to them in any way. They had to specifically dictate all spelling and punctuation (and tabbing).
參賽者不允許看他們的程式碼或是反悔已經唸過的程式碼, 他們必須唸出所有的標點符號跟空白和Tab

The challenge for the last round was to write a function that would return true if and only if the string passed to it hadmatching sets of parentheses.
最後一回合的比賽, 參賽者必須寫一個程式, 檢查匹配括號的字串, 如果是則return True

2011年1月15日 星期六

[Python] 用BeautifulSoup解析HTML範例 - 取出統一發票號碼

[Last Updated: 2013-03-11]

BeautifulSoup用來解析HTML真的很好用, 直接透過pip安裝
$ pip install BeautifulSoup

以下的小範例, 示範如何把 財政部稅務入口網-統一發票中獎號碼-101年11、12月 上的統一發票號碼截取出來



觀察網頁的HTML

會發現在每個號碼都有個class t18red標籤


<span class="t18red"> 55138690</font>

搜尋後剛好是7個 (1個特別奬, 1個特獎, 3個頭獎, 2個增開獎), 所以我們就可以針對這個HTML標籤去做解析

程式碼
See Also
財政部稅務入口網 - 統一發票中獎號碼單

2011年1月13日 星期四

[Python] 計算自己已經活了幾天 calculate your age in days

看自己一年半前寫了一篇Java的文章 : 
[Java] 計算自己已經活了幾天 calculate your age in days

最近都在寫Python, 就想說用Python也來寫一個, 還蠻簡單的。

Python版

Result

你已經活了 9479 天

Java版

跟Java版比起來真的是簡潔太多了。

2011年1月11日 星期二

[Python] 時間格式轉換(strtime & strftime)

strftime 將 datetime object 轉換成String
strptime 將 datetime string 轉換成object

>>> datetime.now()
datetime.datetime(2011, 1, 11, 16, 19, 5, 211588)

>>> datetime.now().isoformat()
'2011-01-11T16:20:06.161541'

>>> datetime.strftime(datetime.now(), '%Y-%m-%d')
'2011-01-11'

>>> datetime.strptime(datetime.now().isoformat(), '%Y-%m-%dT%H:%M:%S.%f')
datetime.datetime(2011, 1, 11, 16, 24, 18, 411861)


See Also

http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior

2011年1月6日 星期四

[Python] convert Unicode to Big5

有時候抓出來的中文unicode字串像這樣 \u55ae\u8eca

結果找一堆資料, 試了unicode, encode, decode都試不出來

結果昨晚就到Stack Overflow去問問看, 果然有一堆好心人幫忙回答

沒想到只要unicode-escape就解決了

str = '\u55ae\u8eca' # It mean '單車'
print str.decode('unicode-escape')

See Also

How to convert utf-8 string to big5 with python? - Stack Overflow

2011年1月5日 星期三

[Python] 安裝Pyflakes Python語法檢查工具及設定Komodo Toolbox

pyflakes 是用來檢查Python程式語法用的, 可以提示未命名的變數或是沒用到(unused)的變數


passive checker of Python programs


Pyflakes is program to analyze Python programs and detect various errors. It works by parsing the source file, not importing it, so it is safe to use on modules with side effects. It's also much faster.


檢查結果如圖所示





2011年1月4日 星期二

[Python] Convert dateime string by Twitter 轉換從 Twitter API 抓出來的時間

轉換從 Twitter API 抓出來的時間

Twitter API抓出來的時間 Created_at 會像這樣

Tue Jan 04 05:27:30 +0000 2011

所以要轉換成自己要的格式才能存進資料庫

from datetime import datetime, timedelta

created_at = 'Tue Jan 04 05:27:30 +0000 2011'
utc_offset = '28800' # +0800   60 * 60 * 8

created_at = datetime.strptime(created_at, '%a %b %d %H:%M:%S +0000 %Y')
local_time = created_at + timedelta(seconds = int(utc_offset))

print created_at
print local_time

Result
2011-01-04 05:27:30
2011-01-04 13:27:30

抓出來的時區是+0000, 所以要再加上UTC_Offset, 才會是本地時間


See Also

Python Documentation - 8.1. datetime — Basic date and time types
在 app engine 使用 pytz
Twitter API Documentation

2010年12月30日 星期四

[Python] Threading Sample - 執行緒範例

每一秒加一個Thread

每一個Thread Sleep 10 seconds

Result:
sleeping 10 sec from thread 0
sleeping 10 sec from thread 1
sleeping 10 sec from thread 2
sleeping 10 sec from thread 3
sleeping 10 sec from thread 4
sleeping 10 sec from thread 5
sleeping 10 sec from thread 6
sleeping 10 sec from thread 7
sleeping 10 sec from thread 8
sleeping 10 sec from thread 9

[Python] 將List 內的項目轉換型態

>>> a = ['1', '2', '3', '4']
>>> a
['1', '2', '3', '4']

>>> a[:] = [int(x) for x in a]
>>> a
[1, 2, 3, 4]

See Also:
http://stackoverflow.com/questions/4561113/python-list-conversion

2010年12月28日 星期二

[Python] Convert String to List 字串轉串列

我把一個List ['aaa', 'bbb'] 存到資料庫

讀出來時會變成 "['aaa', 'bbb']" 字串

所以如果要一一列出時

l = "['aaa', 'bbb']" # 從資料庫讀出的

for v in l:
  print v

會變
[
'
a
a
a
'
,
b
b
b
'
]

所以要先用eval() 把 String 轉回 List即可

for v in eval(l):
  print v

aaa
bbb


See Also:
http://docs.python.org/library/functions.html#eval

[Django] Model中的null 和 blank 設定與差異



models.CharField(max_length=200, null=False, blank=True)

Django的驗證, 預設每個攔位都是為必要的(required)

所以如果你想要將欄位設為空值, 必須再另外設定

在Django的Field有兩種值可以設定: blank and null

blank 只是用於Django自己的input欄位驗證 (Django’s input validation)

Null 是否允許讓你在Database裡插入NULL, 就是空值 (whether the database accepted NULL)

Null = Python的None = 不存在

blank = True 欄位檢查允許為空值
blank = False 欄位檢查不允許為空值
null = True 寫入資料庫允許為NULL (Python 為 None)
null = False 寫入資料庫不允許為NULL (Python 為 None)

See Also:
http://www.b-list.org/weblog/2006/jun/28/django-tips-difference-between-blank-and-null/

2010年12月27日 星期一

[Django] list all Session

for k in request.session.keys():
    print ' key = ', k
    print request.session.__getitem__(k)

See Also:
django - How to use sessions

2010年12月13日 星期一

[Django] Getting Started part 2 - 設置與同步資料庫

Step 1: 編輯setting.py

設置DATABASE的ENGINE and NAME, 在這我用sqlite

such as:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'mysite.sqlite',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}


Step 2: 同步資料庫

python manage.py syncdb

syncdb會根據setting.py裡INSTALLED_APPS的內容來建立需要的資料庫


你可以透過SQLite Manager來查看建立了哪些資料表
http://code.google.com/p/sqlite-manager/
Related Posts Plugin for WordPress, Blogger...