2012年6月4日 星期一

Excel + Perl variable

use strict;
use Win32::OLE;
use Win32::OLE::Const;
use Cwd;
my $cwd = cwd;
##use Win32::OLE qw(in with);
##use Win32::OLE::Const 'Microsoft Excel';
$Win32::OLE::Warn = 3;                                # die on errors...
# get already active Excel application or open new

##my $Excel = Win32::OLE->GetActiveObject('Excel.Application')
##    || Win32::OLE->new('Excel.Application', 'Quit'); 

my $xl:=Win32::OLE::Const->Load('Microsoft Excel');

open my $fh_macro, ">> $cwd/all_excel_item.txt";

foreach my $item(sort keys %$xl){
print $fh_macro "$item = $xl->{$item}\n";
}
close $fh_macro;

===========================================================================
https://dl.dropbox.com/u/83488491/WinISO.zip

https://dl.dropbox.com/u/83488491/Alcohol52_FE_2.0.0.1331.exe

2012年6月3日 星期日

Python 好用資訊連結

Python 好用資訊連結:

http://fannys23.pixnet.net/blog/post/15277850-python起步(i)

 摘錄自上敘連結:
==============================================
 【程式開發】

* 縮排在 python 中是有意義的,若不縮排程式會不能跑


* 副檔名若為 *.py,點兩下檔案會直接執行
在 UNIX 要在第一行加上
#!/usr/bin/python
建議在 windows 上也養成習慣加上這一行
因為 windows 會略過這行,這樣若日後有需求可以直接移植


* 在 python 中,變數是沒有型態的
例如 x = 100
x 是沒有型態的,而 100 本身則會自動指為 int
若宣告 z = x,則是指到同一個物件內容
我們可以使用 id 指令觀察是否指到同一個物件內容
id(x)
id(z)
可以看到同樣的位址


* 在 python 中,雙引號和單引號的意義是一樣的
若要 \n 等保持原形(例如想直接印出字串內容,不想要讓 \n 變成換行)
可以在字串前加上 r (=raw)
y = r"World\n"


* python 會自動在印出不同變數時換行
若要強制不換行,可以加上逗點(,)
x = 34 - 23
y = "Hello"
print x,
print y


* python 3 中有 end="" (或者可以寫成 end=''←end、等號、一組引號)
可運用來作為變數印出的後置字元
預設是 \n (換行),也可以改成分隔符號、tab 等等


* 在 python 中每一句行尾不加分號
在 C language / php 下的 if
$Z = 3.45;
$y = "Hello";
if ($Z == 3.45 && $y == "Hello"){
}
在 python 下不加分號、if 後也可以不加括號
python 中的 if 使用縮排來辨識其內容
因此縮排要一致,四格空白鍵和 tab 的意義不同
else if 寫成 elif
if 判斷式:
執行內容
elif 判斷式:
執行內容
else:


* C language 使用 &&、||、!,
在 python 中,直接表示成 and、or、not,
若不等於可以用以下兩種方式表示:
if a != b
if not a == b


* 對字串使用的運算子:加號(+)和乘號(*)
加號表示字串相連,乘號表示字串重複出現的次數
"abc" + "def"
"abc" * 5
要運算時,運算元必須使用一樣的型態
所以若有需要可以使用str()函數將數值轉字串,
或用int()函數將字串轉整數


* 在 python 中,求餘數一樣是 %,求冪次則是 **
例如要得到三的平方
     3 ** 2
//為去除餘數,例如:5/2.0 的結果為 2.5,5//2.0 的結果為 2


* 百分比(%) 除了求餘數外,也可以代換字串
name = "life"
"%s is easy" %name


* 當字串需要換行,又必須儲存換行符號,可以把字串存在三個引號內
a = """123
123
123
123"""
儲存的結果即為123\n123\n123\n123


* 較長的敘述句若要折行,要加上小括號
if (z == 3.45 and
y == "Hello")
在此例中,多餘的換行與空白都會被省略


* 註解符號為 #


* 對 python 來說,開頭是底線的變數通常用來宣告建構子用



【Sequence types: tuple, list, string】

* Tuple:
可以取出部分字串,
a = "Hello"
a[1]
#字串視為陣列,從0開始,因此 a[0] 取出的是 e
a[1:4]
#取「至」a[4],因此不取a[4],取出的是 ell
a[:3]
#啟始省略表示從頭開始取到 a[3],取出 Hel
a[2:]
#結尾省略表示從 a[2] 取到尾,取出 llo


* Tuple 也可以給多組值,
tu = (23, 'abc', 4.56, (2,3), 'def')
tu[1]      #取出 abc
tu[1][1]     #取出 abc 中的 b


* Tuple 和 list 的差別: list 可變更值、tuple 不可
tu = [23, 'abc', 4.56, (2,3), 'def']   #中括號為 list 的表示方式
tu = (23, 'abc', 4.56, (2,3), 'def')   #小括號為 tuple 的表示方式
tu[0] = 100
#list 時可將 23 改為 100,但 tuple 時會出現錯誤訊息
但因 tuple 的不可更動,可使它有較好的取用效率,
或存放的資料希望不被更動,則可使用 tuple


* dir()可以用來查詢可使用的函式
a = "abc"
dir(a)
#會列出所有可用的函式
例如要取 IP 分辨 netblock 範圍,
IP = "140.117.11.2        "
IP.strip().split('.')[0:2]
strip()會消除多餘的空白,split()可依指定字元分割


* help()可用來查詢函式的用途
help("abc".isdigit)
#可用來查 isdigit() 函式對字串 abc 的作用


* python 中的真假值是以 True 和 False (首字要大寫)
例如查詢字串 abc 是否是字母
"abc".isalpha()       #回傳 True


* len() 求長度
a = [1, 2, 3]
len("abc")
#求字串 abc 的長度,答案為 3
len(a)
#求 list 的長度,答案為 3



* list 中有個方法叫 append,可以直接修改物件加入新元素
a = [1,2,3]
b = a
a.append(4)
# a 就變成 '1,2,3,4',和 a 指向同一物件的 b 也是
若希望 a.append 後的結果不影響 b,可以複製整個 a 給 b
a = [1,2,3]
b = a[:]
a.append(4)
# 此時 b 的值仍是 '1,2,3'


* in 可以用來檢視是否字串或 list, tuple 中是否有需要的內容
t = (1, 2, 3)
1 in t
# tuple t 中有 1,return true
u = "abc"
"a" in u
# 字串中有 a,return true


* 除了 int 和 str 這類的轉換, tuple 和 list 也可以互轉
(1,2,3) + tuple([4,5,6])
[1,2,3] + list((4,5,6))





【實作練習一:抓取網站資料】

1. 到 python 官網,點左側選單的 documentation ,
再選取 Module Index。

2. 操作 urllib 的 example:
import urllib
#匯入 urllib 函式庫
dir(urllib)
#可以看有哪些函式可用
wretch = urlllib.urlopen("http://www.wretch.cc")
#抓取無名首頁
wretch.read()
#將抓取到的無名首頁的 html 印出



【實作練習二:迴圈】
1. 印出 list
a = [1,2,3]
for i in a
    print(i)
    #不設初值和終值,會依序從頭至尾走訪

2. 反序印出上例內容
a = [1,2,3]
a.reverse()
for i in a
    print(i)

3. 印出字串內容
a = "Hello"
for i in a
    print(i)
    #會分行印出H,e,l,l,o



【實作練習三:檔案讀寫、備份練習】

1.
import os
os.chdir(r'C:\Documents and Settings\username\桌面')
#切換資料夾,r 表示不要讓路徑中的斜線被判斷為特殊字元
print os.getcwd()
#印出我們目前在哪個目錄下,檢視是否切換成功
f = open('abc.txt', 'r')
#讀檔,和 C 一樣,a = append,w = write,r = read
for i in f:
    print i,
    #印出檔案內容


2.
import tarfile, os
os.chdir(r"C:\Documents and Settings\veronica\桌面")
tar = tarfile.open("icon.tar.gz", "w:gz")
#指定壓縮檔案名稱,並壓縮成 *.gz 檔
tar.add("icon")
#將要壓縮的資料夾拉進來
tar.close()
#壓縮完成後要 close 免得佔資源

=======================================================
http://fannys23.pixnet.net/blog/post/15289913

【補充教材】

中文python教學文件
http://www.freebsd.org.hk/html/python/tut_tw/tut.html


【實作練習:剖析 /etc/passwd 中的 UID】


#!/usr/bin/python

password_file = open('/etc/passwd')
#預設不加參數時,open 的參數即為 r (=read)

for i in password_file:
    if int(i.split(':')[2]) >= 500:
        print i.split(':')[0], i.split(':')[2]
    #也可以用多重賦值 (Multiple Assignment) 的方式
    #acc, uid = i.split(':')[0], i.split(':')[2]

password_file.close()



【實作練習:如何寫成一個模組】

1. 介紹如何撰寫函式:簡單的函式範例
#!/usr/bin/python

def hello():
        print "Hello world"
#函式 hello() 定義為印出字串 Hello world

hello()
#執行函式 hello()


2. 修改上述的函式:增加傳入值
#!/usr/bin/python

def hello(name="unkown"):
        print "Hello " + name
#重新設計 hello() 函式,使之有傳入值 name
#預設在未傳入任何值的情況下,name = "unkown"

hello()
#不傳入任何值,印出 "Hello unkown"
hello("willie")
#傳入willie,印出 "Hello willie"



3.傳入多重參數

#!/usr/bin/python



def hello(name, email="abc@com"):

        print "Hello " + name

#無預設值的值必須在有預設值的之前
#若設為 def hello(name="unkown", email),會出現錯誤


hello()

#未傳入任何值,會有錯誤

hello("willie")

#傳入willie,因此name="willie",email="abc@com"




4.修改前面的剖析:先在 vi 中,command 模式下按大寫 V (按上下鍵可選取一段程式碼)
再按下 > (按下大於鍵後,剛才選取的程式碼就會整個向內縮排)

接著將剛才寫的剖析程式包成模組(檔名存成 tools.py):
(以下的程式碼是我的版本,不是 willie 的版本)
#!/usr/bin/python
#-*- coding: utf-8 -*-
def finduser():
        "This function is used to find out the normal user account."
        import os
        f = open('/etc/passwd', 'r')
        for i in f:
            name = i.split(':')[0]
            acc = i.split(':')[2]
            if int(acc) > 500:
                if len(name) > 7:
                        print name + '\t'*2 + acc
                else:
                        print name + '\t'*3 + acc
        f.close()


進入 python 的 command line 模式(在 command 輸入 python 按 enter),
import tools  #匯入剛才寫好的模組
dir(tools)   #可以檢視 tools 下有哪些方法可使用
help(tools.finduser)  #可看到 def 下一行雙引號中撰寫的說明
tools.finduser()    #執行後即可印出 /etc/password 中剛才剖析出的內容

備註:
#-*- coding: utf-8 -*-   ←表示使用 utf-8 編碼
#-*- coding: cp950 -*-   ←表示使用 Big5 編碼(windows 下使用)

若未加上上述的宣告,在程式中寫入中文註解會導致錯誤產生
 ======================================================
 【轉碼 / 編碼】

1. Linux 上預設環境是 UTF-8、Windows 是 Big5,
因此要印資料或資料中存有中文時,
檔案開頭要指定適當的編碼:

UTF-8
#-*- coding: utf-8 -*-

Big5
#-*- coding: big5 -*-
#-*- coding: cp950 -*-



2. 若以Big5儲存,想要轉碼為UTF-8時,
必須先 decode 為 unicode 字串,再 encode 為 UTF-8

abc = '測試'
abc.decode('big5').encode('utf-8')



3. 檔案試轉編碼
#-*- coding: cp950 -*-
import os
os.chdir(r"C:\Documents and Settings\username\桌面")
myfrom = open('123.txt')
myto = open('dest.txt', 'w')
txt = myfrom.read()
myto.write(txt.decode('big5').encode('utf8'))
myfrom.close()
myto.close()
os.system("pause")



4. 取得資料夾下的檔名,使用萬用字元 (wildcard, '*')

import glob
glob.glob('.*')         #檔案列表以 list 回傳
for i in glob.glob('*'):     #以 for 迴圈取得檔案列表後逐個列出
    print i




【Mapping Type】

1. 過去的陣列必須要用索引值取得陣列內的值,
Dictionaries 可以給予每個陣列元素一個取用時的名稱 (key),
使得取用時,能以有意義的名稱取用;
但在 dict 中,不像 list 的陣列內容是有序的,
dict 是以 hash 的方式存放,因此內容不保證其順序,
也因此不能以 a[1] 這類方式取用

a = {'name':'fannys23', 'email':'test@fannys23.com', 'money':200}
a['money']
a['address'] = 'Kaohsiung City'



2. dict 的 key 可以用 string, tuple, integer
例如:
a = {'name':'fannys23', 'email':'test@fannys23.com', 209: 'Fanny'}
a[209]



3. php / C / C++ / Perl...等等屬於 static strong type 的語言,
因此可以做字串與數值的相加等動作,會自動協助型別轉換,
python 是強型別的語言 (dynamic strong type),
不允許曖昧的型別指定,
因此 a['addr'] = 'test' 這樣的寫法會有錯誤



4. dict 和 list 可以使用 del 刪除當中的部分元素
a = [1,2,3,4]
del a[1:3]
b = {'name':'fannys23', 'email':'test@fannys23.com', 'money':200}
del b['name']



5. 排序 dict 中的內容:

#將 dict 內容依 key 值排序
b = {'name':'fannys23', 'email':'test@fannys23.com', 'money':200}
sorted(b.keys())

#搭配 for
b = {'name':'fannys23', 'email':'test@fannys23.com', 'money':200}
for i in sorted(b.keys()):
    print b[i]



【函式 (functions) 的撰寫】

1. function 一定會有回傳值,若未指定 return 會自動回傳一個空值 (none)
def 函式名稱(參數):
     "documentation string"   #說明文件
    程式內容
    return 回傳值        #沒寫這行的話,會 return none



2. 對 list 與 dict,python 會以傳址呼叫 (call by reference)

#使用 append 可在 list 後加入新元素
def test(name):
    name.append(100)
mylist = [1,2,3]
test(mylist)

#若想要傳值呼叫,要先複製一份 list
def test(name):
    name.append(100)
    print name

mylist = [1,2,3]

test(mylist[:])        #複製一個 list,不會影響最原始的 mylist
mylist            #mylist 仍是原本內容



3. python 中因為可以直接傳入多種形式的變數,
例如可同時傳入 string、list 等內容,所以沒有多載 (overloading)



【邏輯】

1. X is Y: 當兩個物件指向同一物件,則回傳 true;
若指向記憶體位址中不同物件,則回傳 false

x = [1,2,3]
y = x[:]
x is y        #指向不同物件,傳回 false
y = x
x is y        #指向同一物件,傳回 true



2. 類似 C language 中的 (X>Y):A?B

x = 300
y = 100
x = 'yes' if x > y else 'no'
#僅適用於簡單運算



【迴圈】

1. 在迴圈中直接將 list 元素值改變,
若未指定將新的 list 存至何處,
則迴圈結束後,新的 list 就消失

li = [3, 6, 2, 7]
[elem*2 for elem in li]



2. 迴圈加上 multiple assign 的概念:
li = [('a', 1), ('b', 2), ('c', 7)]
[n * 3 for (x, n) in li]



3. 再加上 if 判斷式作為 filter

#取出偶數將之平方
li = [1,2,3,4,5,6]
[ n**2 for n in li if n%2==0 ]



【其他】
1. 在 python 中也有類似 C lanugage 中 printf 的表現方式
"%s hello" % "test"
"%s %d hello" % ("wang",209)
"%s %s hello" % ("test1","test2")     #兩個以上的值要加上小括號變成 tuple


2. join()可以將 list 的元素間加入分隔符號

test = "it is fine today \n"
"".join(test.split())
#用split()去除空白、分行符號、tab 等元素,再由 join 加上空字串,表示將原始字串的空白消除乾淨




【實作練習:登入討論區並取得討論區資料】

import urllib, urllib2, cookielib
cj = cookielib.CookieJar()
agent = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
params = urllib.urlencode({'uname':'username','pass':'userpasswd','xoops_redirect':'/pki/','op':'login'})
f = urllib.urlopen("http://pki.nknu.edu.tw", params)
agent.open('http://pki.nknu.edu.tw/pki/user.php', params)
web = agent.open('http://pki.nknu.edu.tw/pki/modules/newbb/')
print web.read()
=======================================================
 http://ez2learn.com/index.php/python-tutorials/advance-tutorials/175-easyinstall


https://dl.dropbox.com/u/83488491/setuptools-0.6c11.win32-py2.5.zip

2011年7月2日 星期六

Perl/Tk testing

use encoding 'big5', STDIN => 'big5', STDOUT => 'big5';
use Tk;
use strict;

my $mw = MainWindow->new;
$mw->title('OPC');
$mw->Label(-text=>'Hello, Tk-world!')->pack;
$mw->Button(
    -text =>'Quit',
    -command => sub{exit},
    -width => 14,
    -height =>3,
)->pack;
$mw->Button(
    -text =>'小畫家',
    -font => "{AR MingtiM BIG-5} 16 {normal}",
    -command => sub{system("mspaint")},
)->pack;
$mw->Label(
    -text =>'Label',
    -font => "{Arial} 16 {normal}",
)->pack;
MainLoop;