跳到主要內容

發表文章

目前顯示的是有「Python」標籤的文章

[Python] 輸出二進位檔案

記錄一下 python 如何輸出成二進位檔案。 我輸出二進位檔案的方法,採用的是 bytearray 這個函式。 我會先把我要輸出的數字,以 byte 為單位,先放入一個 list 陣列,然後將 list 陣列用 bytearray 轉成 byte 格式,寫入檔案: #!/usr/bin/env python3 import struct def main (): outputFile = open( "tmp.bin" , "wb" ) byte_dat = [ 0xab , 0xcd , 0xef ] binary_pack = bytearray(byte_dat) outputFile.write(binary_pack) outputFile.close() if (__name__ == "__main__" ): main() 我們用 Linux 的 xxd 指令 一個一個 byte 看一下輸出的檔案長什麼樣子: 在終端機輸入: xxd -g1 -c1 ./tmp.bin 輸出結果: 00000000: ab  . 00000001: cd  . 00000002: ef  . 可知第一個 byte 是放在陣列 index 0 的位置,第二個 byte 是放在陣列 index 1 的位置,餘類推。

[Linux] 安裝 conda 並用 conda 安裝套件

本篇文章介紹 conda 在 Linux 安裝與基本使用方法。 conda 是一個套件包管理器,跟 apt-get 一樣。conda 的宗旨最初是為了管理複雜的 Python 語言包安裝,後來開始支援其它語言包的安裝(例如 R 語言)。 在 Linux 安裝 conda 指令無法採用 apt-get 指令,要安裝 conda 有兩種方式: 安裝 Anaconda。Anaconda 是一個 Python 的發行版,專門用於計算科學,內建很多的預設數據科學的軟體包,因此會安裝 Anaconda 會需要較大的硬碟空間,會安裝約 3 GB 大的檔案到電腦內。 安裝 Miniconda,是最小安裝版本的 Anaconda,內建 conda、Python 和一些基本套件和基本工具。我目前是安裝這個,因為我不想要安裝一些目前還用不到的語言包。 Minicoda 可以在 這個網站 下載。 我選擇 Python 2.7 的 Linux 64-bit 版本下載,安裝過程 不需要使用 sudo 權限 ,否則之後 conda 執行上會有權限問題,conda 在執行的時候是無法使用 sudo conda ... 來執行指令的。 安裝過程如下(作業系統為 Linux 發行版:Elementary OS): 執行 (不需要加 sudo)  bash ./Miniconda2-latest-Linux-x86_64.sh 會出現歡迎畫面: Welcome to Miniconda2 4.7.12 In order to continue the installation process, please review the license agreement. Please, press ENTER to continue >>> 按 Enter 後,閱讀完授權合約,輸入 yes 接受合約條款。 Do you accept the license terms? [yes|no] [no] >>> 預設安裝路徑是家目錄的 minicoda2,按下 Enter 可即刻安裝。 Miniconda2 will now be installed into this...

[Python] Call by reference

Python 有 call by reference 嗎? 有的。在預設情況,傳入 mutable object 給一個函式,那個函式會將那個物件用傳參考的方式處理。 但是如果在函式內將物件的參考指向其他的地方,在這樣的情況下,不會改變傳入物件的內容的,因為 Reference Object 指向別的地方,並不會影響原本傳入物件指向的記憶體位置: 什麼是 mutable object? 在物件導向中,mutable object 就是指可變物件,在物件一生成時,物件內容還能改變。 Python 的 list 就是 mutable object,但 string 不是。 詳細的說明 參考這裡 。

[Python] 單引號,雙引號和三引號

在此解釋各種引號的意義。 雙引號跟單引號,在 Python 中的基本上沒差別,都可以代表字串: "This is a string" 'This is a string' 並且雙引號內可包含單引號,反之,如果用的是單引號,則單引號內可包含雙引號: "We call it 'Dog'...... " 'We call it "Dog"...... ' 三個雙引號,就可以直接輸入有換行的字串: """haha, this is a dog.""" 三個單引號要換行,就要輸入"\": '''haha, \ this is a dog.'''

[Python] dictionary 基本用法

Perl 有 hash,python 有 dictionary。 Dictionary 的用法,可以想成一個陣列裡面,每個元素裡面存的是一個 key 值,以及那個 key 值對應的 value。在 python terminal 可以測試以下程式,就可以了解 dictionary 使用方法: dict = {'name': 'Jack', 'gender': 'male'} print "name: ", dict['name'], " gender: ", dict['gender'] 執行結果: name:  Jack  gender:  male 判斷一個 value 是否存在: if 'Jack' in dict.values()   # exist -> return Ture 判斷一個 key 是否存在: if dict.has_key('name'):   # exist -> return True 初始化一個空的 dictionary: dict = {} 回傳某個特定的 value 的 key 值: 只能用 for 迴圈了... 如下: for key in dict:     if dict[key] == 'Jack':         print " I find: ", key 執行結果:  I find:  name 增加一個 item 在 dictionary 內: dict['new_key'] = 'item' 或者: dict.update({'new_key', 'item'})

[Python] Parse 左右括號內的變數宣告

以前做研究時,常用正規擷取兩個括號之間的 Attributes,用一個例子解釋如下。 假設今天有一個檔案內容,描述一筆資料結構: Person Tom{                       name    Tom,                       age        20,                       gender  male                    }; 如果想擷取出: 1 : Tom 2 : 20 3 : male 用 Python 的 regex 具體作法,我分成兩步驟: 先將檔案內容從 Person 開始到結尾分號,存入一個 string 叫做 full_line,但注意不要存 \n 換行字元到 full_line 內。 用正規將 full_line 內大括號內的字元都擷取出來,也就是擷取: "name Tom, age 20, gender male" 再利用正規,將第 2 步驟擷取出的字串,用 re.findall 逐一擷取 attributes 的 key 值。  Code 如下: full_line = "" with open(fileName, 'r') as f: for line in f.readlines(): line = line.strip() if not line: continue // eliminate lines filled with white spaces pri...

[Python] print 同時輸出到 file 和 console

在 Python 撰寫程式時,我們會希望螢幕 stdout 輸出可以同時記錄到 log 檔案裡。 但是螢幕輸出可能含有 ASCII escape codes 的顏色資訊,輸出的 log 檔案會有類似 ^[[01;32m 這種字樣出現。 我採用比較簡單的解法: 先將 print 函式輸出的訊息,同時導向到螢幕,同時儲存在指定的 log.txt 檔案中。 再用 sed 指令,將 log.txt 內的 ASCII escape code 清除。 方法如下: import sys class PrintLog(object): def __init__(self): self.console = sys.stdout self.log_file = open("log.txt", "w") def write(self, msg): self.console.write(msg) self.log_file.write(msg) def flush(self): pass def main(): original_stdout = sys.stdout sys.stdout = PrintLog() print " This is a testing message." sys.stdout = original_stdout if(__name__ == "__main__"): main() 也就是將 sys.stdout 指向自定義的 PrintLog class,讓 PrintLog 來處理輸出文字,用完 PrintLog 後再把 sys.stdout 導向回原本的 stdout。 接著使用 sed 指令刪除 log.txt 的 ASCII escape code: sed -i 's/\x1b[^m]*m//g' ./log.txt 上面的正規,\x 後面用來接一個 16 進位 ASCII 編碼,其中 1b 代表的是 ESC 退出鍵。 到此即可獲得沒有顏色編碼的 log.tx...

[Python] 正規表達式 Regex:group

記錄正規表達式的 group 擷取字串的順序。 Python 的正規表達式,透過 group() 函式擷取括號框住的內容。 以下是我寫的例子: import re def main():     string_to_search_1 = "food   @123"     string_to_search_2 = "feed"     pattern = re.compile(r'(f(oo|ee)d)\s*(@(\d+))*')     matches = pattern.finditer(string_to_search_1)     for match in matches:         print "match:", match.group()         print "1:", match.group(1)         print "2:", match.group(2)         print "3:", match.group(3)         print "4:", match.group(4)         # print "5:", match.group(5)  # no such group.         tmp = int(match.group(4))         tmp += 5         print "tmp =", tmp         tmp = str(match.group(4))         print "tmp[2] =", tmp[2]     matches = pattern.find...