bloggerads

2017年9月14日 星期四

Python : JSON

鑒於JSON愈來愈普及, 很多數據都要求使用JSON的格式,因此特別在這篇做個紀錄, 了解JSON以及如何用Python處理JSON。  

了解 JSON 的 format可以從這個
網站開始: http://jsoneditoronline.org/



#  JSON的規則:

1.  key:value
2.  value 型態可以是 數字, 字串, 布林, 陣列[], 物件{}, NULL, 但key一定是要字串
3.  同一個物件內的key不可重複, 如以下的 Age 就重複了
{
    "Martin": {
        "Age":33,
        "Age":5,
     }
}

2017年9月10日 星期日

Python : regular expression

re module的一些紀錄, 持續update

### Common use of the regular expression

\w   [a-zA-Z0-9_]
\d    [0-9]
\s    space
\\     '\'
.       ''
+     1 or more than 1
.\     everything

### Code

>>> import re
>>> string = 'Age=20'
>>> re.search('\d+', string).group()
20

>>> import re
>>> string = 'Beautiful, is; better*than\nugly'
>>> # 分隔符號:,  ;  *  \n
>>> list= re.split(',|; |\*|\n', string)
>>> list
['Beautiful', 'is', 'better', 'than', 'ugly']

2017年9月5日 星期二

Python : Combobox 範例

距離上次Python文,不知不覺又過了兩三個星期了。 時間過得真快,這段時間除了工作外,還去了花蓮玩兩天! 雖然工作上每天都在改code, 但使用到Python的機會很少,本著學海無涯,惟勤是岸的精神,隔一段時間就來po 一下,以免生疏了。今天介紹Combobox,搭配Button作範例,話不多說,馬上端上code:

#! python2
# coding: utf-8

import Tkinter as tk
import ttk   

def clickOkButton():
    print 'Select ' + str(numberChosen.current()) # 丟出選到的index number

win = tk.Tk()
win.title("Python Combobox example") 

2017年8月14日 星期一

Python : 透過字串與數字轉換來做"進制轉換"

所有的非10進制數字都要以字串的型式表達,而數字一律是10進制表示。

因此進制轉換就只是字串轉數字或數字轉字串的差別。以下就針對這兩種狀況來說明。

● 字串轉數字

>>> int ('0x10', 16)  #必須告訴直譯器字串是哪種進制
16

2017年8月13日 星期日

Python : Tkinter (Button, Label, Entry, Listbox)

Tkinter 並不是一個很強大的GUI library, 但優點是, 他是Python官方支援的module, 且大部分的OS都有預先安裝它<Note 1>。 之後陸續出現的第三方GUI library相信都是由他啟發的。因此如果不是開發太複雜的GUI tool, 又想了解這個歷史悠久的library, 那就值得來了解他。

話不多說,直接上code:

step 1. 先來創一個空的視窗

from Tkinter import *
    
win = Tk()
win.title("Tk Gui")
win.resizable(width=False, height=False)
win.geometry("500x250")

win.mainloop()


Python : 調用模組的語法比較

以調用random模組中randint函數,印出隨機數字0~10來作範例

1. 函數呼叫透過: 模組.函數() 
    import random
    print random.randint(0,10)

2. 直接呼叫函數(), 但必須告訴直譯器調用模組中的哪個函數
    from random import randint
    print randint(0,10)  

3. 直接呼叫函數(), 直接告訴直譯器要引用模組中所有的函數。 會有函數名稱衝突的風險!
    from random import *
    print randint(0,10)

4. 在script中定義模組的新名稱, 呼叫方式: 模組新名稱.函數()
    import random as newname
    print newname.randint(0, 10)

2017年8月11日 星期五

Python : tuple, list, set, dict 整理與比較


python常用的四種container types: tuple, list, set dictionary

tuple: ()
    - save in order
    - read only
list: []
    - save in order
set: {}

dictionary: {key:value}

NOTE:
t = tuple([1,2,3])
>>>t[0]
1