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

2019年11月10日 星期日

Python語言學習索引

檔案

資料結構

命令行

方法

小專案

其他


如果你覺得這篇文章很有用,可以請我喝杯咖啡,讓我提供更多優質文章給您。感謝所有支持的朋友。

Vere Perrot 資訊人.科技人.行銷人,現為軟體分析師。定位自己為網路觀察家,永遠保持好奇心與熱情,學習跨領域新事物,希望最終能成為一個全方位的人。 Mail: vereperrot@gmail.com

2019年1月31日 星期四

Python檔案讀寫


如果你覺得這篇文章很有用,可以請我喝杯咖啡,讓我提供更多優質文章給您。
感謝所有支持的朋友。


Vere Perrot
資訊人.科技人.行銷人,現為軟體分析師。定位自己為網路觀察家,永遠保持好奇心與熱情,學習跨領域新事物,希望最終能成為一個全方位的人。
GitHub: github.com/perrot | Mail: vereperrot@gmail.com

2017年3月5日 星期日

anaconda教學

安裝Anaconda

  1. 下載Anaconda
  2. 下載我系統的安裝檔 Windows 10 64 bits

啓動Python IDE

  1. 在cmd命令行執行指令 "spyder"
  2. 或你可以建立一個捷徑,將目標欄位指定為"spyder"

更新spyder

在cmd命令行執行指令 "pip install --upgrade spyder"

2016年12月30日 星期五

四、改善神經網路學習的方式

資源

訓練神經網路是不容易的。有時他們沒有學全(欠擬合)。有時他們學習的準確,你給他們什麼,他們的知識不能歸納出新的,無形的資料(過擬合)。這裡有很多方法可以來處裡這些問題。




工具

這裡有很多架構提供標準的演算法,並對硬體做了最佳化。很多架構有Python介面,像Torch例外,就需要Lua。一但你知道基礎的學習演算法如何實作。是時候選擇一種架構來建製它。




這裡也有許多高階的架構,運行其上:


  • Lasagne是一個高階的架構,建立在Theano之上。提供簡單的函式來建立一個巨大的網路,只需要幾行程式碼。
  • Keras 是一個更高階的架構,運行在Theano或 TensorFlow之上。
  • 假如你不能確定哪個架構適合你,可以參考這個指導手冊,閱讀 史丹佛課程 CS231n第12講。 ★★

三、基礎神經網路

資源

神經網路是一個強大的機器學習演算法。他們形成了深度學習的基本。


工具

試著從頭實做一個單層的神經網路,包含訓練程序。


深度學習指南

深度學習是一個快速發展的領域,是電腦科學與數學的一個黃金交叉。與之相關的一個新的分支,叫做機器學習。機器學習的目標在於教導電腦基於給定的資料,完成特定的工作。這個指南是為那些想學數學,學程式語言,與想成為深度學習專家而準備的。

這指南不是一個關於:

準備


你必須了解一般大學程度的數學。你必須複習深度學習這本書的最初幾章的觀念:
你必須知道如何程式設計,與測試深度學習模型。我們建議使用Python來做機器學習。NumPy/SciPy函式庫做科學計算。
當你熟悉了準備的材料,我們建議四個選項來學深度學習。選擇任一個,或是任幾個組合來做學習。星號的數量指出該材料的難度。

有許多軟體架構提供必須的函式,類別與模組用於機器學習與深度學習。我們建議你不要使用這些架構,在你早期的學習。取而代之的是,我們建議你從頭開始實做一個基礎的算法。很多課程詳細的解釋演算法背後的數學,所以他們可以簡單的實做出來。

  •  Jupyter notebooks是一個很方便的方式來使用Python程式碼。他們對於matplotlib有很好的整合,有個很方便的工具能讓資料視覺化。我們建議你實做演算法在這樣的環境。 ★

三、基礎神經網路

四、改善神經網路學習的方式

2013年8月21日 星期三

重新命名一個檔案

import os
os.rename(old,new)

字串轉為浮點數

print float('30.00')

#output is 
#30.0

2013年8月20日 星期二

自動偵測字串編碼,使用chardet

  1. 從下面的位置下載chardet。

    https://pypi.python.org/pypi/chardet
  2. 解壓縮後,複製下列路徑下的資料夾。
    chardet-2.1.1.tar\chardet-2.1.1\chardet-2.1.1\chardet
  3. 將資料夾複製到下列路徑。
    D:\Program Files\Python25\Lib\site-packages
  4. 一個範例程式碼如下:
    import chardet    
    rawdata = open(infile, "r").read()
    result = chardet.detect(rawdata)
    charenc = result['encoding']
    
  5. 可以在python的console中,下指令來顯示幫助。
    help(chardet)
    
    如果沒有找到該模組,請先import該模組。
    import chardet
  6. 偵測字串編碼的速度有點慢。
  7. 參考

    http://stackoverflow.com/questions/3323770/character-detection-in-a-text-file-in-python-using-the-universal-encoding-detect

2013年8月19日 星期一

靜態方法

>>> class C:
...     @staticmethod
...     def hello():
...             print "Hello World"
...
>>> C.hello()
Hello World

參考
http://stackoverflow.com/questions/735975/static-methods-in-python

加入元素到元組(tuple)

t=(1,2)
t+=(3,)
參考 http://stackoverflow.com/questions/5756768/adding-elements-to-a-tuple-when-i-know-i-shouldnt-be-able-to

忽略隱藏檔案

if os.name == 'nt':
    import win32api, win32con


def folder_is_hidden(p):
    if os.name== 'nt':
        attribute = win32api.GetFileAttributes(p)
        return attribute & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM)
    else:
        return p.startswith('.') #linux

參考
http://stackoverflow.com/questions/7099290/how-to-ignore-hidden-files-using-os-listdir-python

建立與讀取捷徑(.lnk)


建立捷徑

使用WSH

import sys
import win32com.client 

shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
shortcut.Targetpath = "t:\\ftemp"
shortcut.save()

另一種方法

import os, winshell
from win32com.client import Dispatch
 
desktop = winshell.desktop()
path = os.path.join(desktop, "Media Player Classic.lnk")
target = r"P:\Media\Media Player Classic\mplayerc.exe"
wDir = r"P:\Media\Media Player Classic"
icon = r"P:\Media\Media Player Classic\mplayerc.exe"
 
shell = Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = target
shortcut.WorkingDirectory = wDir
shortcut.IconLocation = icon
shortcut.save()

讀取捷徑使用WSH

import sys
import win32com.client 

shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
print(shortcut.Targetpath)

讀取命令行指令的輸出

import popen2
import os
s="\"D:\Dropbox\Software\7z.exe\" l \"c:\Program files\7-Zip\7-Zip.zip\"".replace('\\','/')
cmdout , cmdin = popen2.popen2(s)
print cmdin
output=""
for line in cmdout: 
 output=output+line
cmdout.close() # Don't forget to close output and input handles
cmdin.close()
print output

檢查檔案是否存在

import os

os.path.exists(filename)

參考
http://stackoverflow.com/questions/82831/how-do-i-check-if-a-file-exists-using-python

附加文字到檔案

with open("test.txt", "a") as myfile:
    myfile.write("appended text")


參考
http://stackoverflow.com/questions/4706499/how-do-you-append-to-file-in-python

2013年2月20日 星期三

用奇摩字典做查詢 - ydict.py

#!/usr/bin/env python
# coding=UTF-8
# Chen Wen 
# Web Site http://code.google.com/p/ydict/
# Blog : http://chenpc.csie.in

import getopt
import sys
import string
import httplib, urllib,string,sys
from HTMLParser import HTMLParser
from optparse import OptionParser
import locale
from codecs import EncodedFile
import shelve,os
import random
import ConfigParser
from multiprocessing import Process, Queue, Pool


version="ydict 1.2.5"
red="\33[31;1m"
lindigo="\33[36;1m"
indigo="\33[36m"
green="\33[32m"
yellow="\33[33;1m"
blue="\33[34;1m"
org="\33[0m"
light="\33[0;1m"
learn=0
browsemode=False
database=0
voicedata = ""
playback = ""
prefetch = ""



if os.access(os.getenv("HOME")+"/.ydict.db", os.F_OK):
    db = shelve.open(os.getenv("HOME")+"/.ydict.db","c")
    learn = 1
    database = 1
try:
    config = ConfigParser.ConfigParser()
    config.readfp(open(os.getenv("HOME")+"/.ydictrc"))
    voicedata = config.get('ydict', 'voicedata')
    playback = config.get('ydict', 'playback')
    prefetch = config.get('ydict', 'prefetch')
except :
    pass

if prefetch == "":
    prefetch = "5"
    
        
def cleanup():
    if database:
        db.sync()
    exit()

def importfile(file):
    fp = open(file)
    for line in fp:
        newword=line.split(" ")[0]
        newword=newword.split("\n")[0]
        if db.has_key(newword) == 0:
            db[newword]=0
    print "File imported!"
def result(count, total):
    if total == 0:
        print ""
        exit()
    print "\nScore: ",int(count),"/",int(total),"(",count/total,")"
    exit()

def seckey(x):
        return x[1]
       
def savefile(k, url):
    if voicedata == "":
        return
    filename = "'"+voicedata+"/"+k[0]+"/"+k+".mp3'"
    if not os.access(filename, os.F_OK):        
        if not os.access(voicedata+"/"+k[0], os.F_OK):
            os.system("mkdir "+voicedata+"/"+k[0])
        os.system("rm -f "+voicedata+"/voice.tmp")
        os.system("wget -q "+url+" -O "+filename+"voice.tmp");
        os.system("mv "+filename+"voice.tmp "+filename)
        
def speek(k):
    if voicedata == "" or playback == "" or k == "":
        return
    
    filename = voicedata+"/"+k[0]+"/"+""+k+".mp3"
    if not os.access(filename, os.F_OK):
        dict(k, m_pron)
    else:                
        os.system(playback+" '"+filename+"' >/dev/null 2>&1 &")

def answers(iq, oq):
    while(1):
        key = iq.get()
        (result,k) = dict(key, 1)
        oq.put([key, result])
        
        
def browse():
    wordlist = db.items()
    size=len(wordlist)
    totalcount = 0.0
    right = 0.0
    lookup = Queue(maxsize = string.atoi(prefetch))
    answer = Queue(maxsize = string.atoi(prefetch))
    lookuper = Process( target=answers, args=(lookup, answer) )
    lookuper.daemon = True
    lookuper.start()

    if size <= 1:
        print "There must be at least two words needed in the list."
        exit()
    i = 0
    while(1) :
        while(not lookup.full()):
            k=wordlist[i][0]
            i = i + 1
            if i >= size:
                i = 0
            k=k.lower()
            lookup.put(k)
        (k, result) = answer.get()
        if not db.has_key(k):
            continue
        print result
        speek(k)                
        
        try:
            word = raw_input("(d) Delete, (enter) Continue: ")
            if word == "d":
                del db[k]                                
                wordlist=db.items()
                size=len(wordlist)
                if size <= 1:
                    print "There must be at least two words needed in the list."
                    exit()                    
        except KeyboardInterrupt:
            result(right,totalcount)            
        
def wordlearn():
    wordlist = db.items()
    wordlist.sort(key=seckey)
    size=len(wordlist)
    totalcount = 0.0
    right = 0.0
    lookup = Queue(maxsize = 5)
    answer = Queue(maxsize = 5)
    lookuper = Process( target=answers, args=(lookup, answer) )
    lookuper.daemon = True
    lookuper.start()

    if size <= 1:
        print "There must be at least two words needed in the list."
        exit()

    while(1) :
        while(not lookup.full()):
            k=wordlist[int(random.triangular(0, size-1, 0))][0]
            k=k.lower()
            lookup.put(k)
        (k, result) = answer.get()
        if not db.has_key(k):
            continue
        if browsemode == False:
            print result.replace(k, "####").replace(k.upper(), "####").replace(k[0].swapcase()+k[1:].lower(),"####")
        else:
            print result
        speek(k)
        word = raw_input("Input :")                
                
        if word == k.lower():
            print "Bingo!"
            right+=1
            db[k]+=1
            if db[k] >= 100:
                db[k]=100
        else:
            db[k]-=3
            if db[k] < 0:
                db[k]=0
            print "WRONG! Correct answer is : ",k
            try:
                word = raw_input("(d) Delete, (enter) Continue: ")
                if word == "d":
                    del db[k]                                
                    wordlist=db.items()
                    wordlist.sort(key=seckey)
                    size=len(wordlist)
                    if size <= 1:
                        print "There must be at least two words needed in the list."
                        exit()                    
            except KeyboardInterrupt:
                result(right,totalcount)
            

        totalcount+=1
        if totalcount % (int(size/4)+1) == 0:            
            wordlist=db.items()
            wordlist.sort(key=seckey)
def wordlist():
    wordlist = db.items()
    wordlist.sort(key=seckey)
    for k,v in wordlist:
        print k,v

class MyHTMLParser(HTMLParser):
    redirect=0
    pron=True
    def __init__(self):
        self.show=0
        self.prefix=""
        self.postfix=org
        self.entry=1
        self.desc=0
        self.result=[]
        self.learn=learn
        self.learnword=0
        self.chinese=0
        self.mp3url=""
        self.key=""

    def handle_starttag(self, tag, attrs):
        if self.redirect == 1 and tag == "strong":
            self.show=1
            self.prefix="Spell Check: ["+yellow
            self.postfix=org+"]"
        
        elif tag == "span" and len(attrs)==0:
            if self.pron == True:
                self.show=1
                self.prefix=""
        elif tag == "div" and len(attrs)==0:
            if self.pron == True:
                self.show=1
                self.prefix=""
        elif tag == "div" and len(attrs)!=0:
            if attrs[0][1]=="pronunciation" and self.pron==True:
                self.result.append(blue)
            elif attrs[0][1]=="caption":
                self.show=1
                self.prefix=red
            elif attrs[0][1]=="theme clr":
                self.show=1
                if self.chinese == 0:
                    self.learnword=1
                    self.prefix="["+light
                    self.postfix=org+"]"
            elif attrs[0][1]=="description":
                if self.desc != 0:
                    self.show=1
                    self.prefix="  "+org
                self.desc+=1
        elif tag == "p" and len(attrs)!=0:
            if attrs[0][1] == "example":
                self.show=1
                self.prefix="    "+indigo
            elif attrs[0][1] == "interpret":
                self.show=1
                self.prefix="  "+org+str(self.entry)+"."
                self.entry+=1

    def handle_data(self,data):
        if self.show == 1:
            self.result.append(self.prefix+data+self.postfix+"\n")
            self.show=0
            self.prefix=""
            self.postfix=""
        if(self.learn == 1 and self.learnword == 1):
            self.key = data.lower()
            if(db.has_key(self.key) == 0 and self.key.isalpha() ):
                db[self.key] = 0
            self.learnword=0
            savefile(self.key, self.mp3url)

    def handle_endtag(self, tag):
        if tag == "div":
            self.result.append(org)

def htmlspcahrs(content):
    content=content.replace("&","&")
    content=content.replace("'","\'")
    content=content.replace(""","\"")
    content=content.replace(">",">")
    content=content.replace("<","<")
    content=content.replace("","")
    content=content.replace("","")
    content=content.replace("",lindigo)
    content=content.replace("",org+indigo)
    content=content.replace("\n","\n    "+green)
    return content


def http_postconn(word):
    yahoourl="tw.dictionary.yahoo.com"
    params = urllib.urlencode({'p': word ,'ei' : 'UTF-8'})
    return urllib.urlopen("http://%s/search" % yahoourl, params)

def dict(word,pron):
    output=""
    word=word.strip()
    if len(word) <= 0:
        return output, ""
    r1=http_postconn(word)
    data1 = r1.read()
    p=MyHTMLParser()
    p.redirect=0
    p.chinese=0
    p.pron=pron
    
    try:        
        index5 = string.index(data1, '{"audio":"')        
        index6 = string.index(data1,'"}};var noFlashPlayerMessage')        
        p.mp3url = data1[index5+10:index6]
    except ValueError:
        p.mp3url = ""
        pass
    
    try:
        data1=data1[:string.index(data1,'

Online Resources

')] except ValueError: return output, word try: index1=string.index(data1,"?冽銝閬") p.redirect=1 except ValueError: try: index1=string.index(data1,"敺甇?摮?曆??唳閬?鞈???") if db.has_key(word): del db[word] return yellow+"Not Found!"+org+"\n", word except ValueError: index1=string.index(data1,"摮??") try: index3=string.index(data1,"隞乩???") index4=string.index(data1," ?典??訾葉????) print yellow+"隞乩???"+light+data1[index3+18:index4]+yellow+" ?典??訾葉????+org except ValueError: pass try: string.index(data1,"?潮") string.index(data1,"瘜券") p.chinese=1 except ValueError: pass data=data1[index1:] p.reset() data=htmlspcahrs(data) p.feed(data) for s in p.result: output+=s return output, p.key if __name__ == '__main__': parser = OptionParser(usage = "Usage: ydict [options] word1 word2 ......") parser.add_option("-s", "--step", dest="step", help="one step mode.",default=False,action="store_true") parser.add_option("-p", "--pron", dest="pron", help="disable pronounce.",default=True,action="store_false") parser.add_option("-u", "--utf8", dest="utf8", help="force utf-8 encoding.",default=False,action="store_true") parser.add_option("-b", "--big5", dest="big5", help="force big5 encoding.",default=False,action="store_true") parser.add_option("-w", "--word", dest="oneword", type="string" , help="only one word.",action="store") parser.add_option("-c", "--nocolor", dest="nocolor", help="force no color code",default=False, action="store_true") parser.add_option("-v", "--version", dest="version", help="show version.",default=False,action="store_true") parser.add_option("-d", "--database", dest="database", help="initial database.",default=False,action="store_true") parser.add_option("-l", "--learn", dest="learnmode", help="start learning mode.",default=False,action="store_true") parser.add_option("-B", "--browse", dest="browsemode", help="start browse mode.",default=False,action="store_true") parser.add_option("-a", "--list", dest="listall", help="list all word in list.",default=False,action="store_true") parser.add_option("-i", "--import", dest="importfile", type="string", help="import a word list",default=False,action="store") (options, args) = parser.parse_args() m_pron=options.pron (lang , enc)=locale.getdefaultlocale() if options.nocolor: red="" lindigo="" indigo="" green="" yellow="" blue="" org="" light="" if options.importfile: importfile(options.importfile) cleanup() if options.version == True: print version cleanup() if options.utf8 == True: enc="utf8" elif options.big5 == True: enc="big5" else: enc="utf8" if options.browsemode == True: try: browse() except KeyboardInterrupt: print "" cleanup() except EOFError: print "" cleanup() if options.utf8 == options.big5 ==True: print "Can not select utf-8 and big5 at the same time" cleanup() if enc == 'big5': m_pron=False if options.oneword: (result, k) = dict(options.oneword,m_pron) speek(k) result=unicode(result,'utf8') result=result.encode(enc) print result cleanup() if len(args) >= 1: for w in args: (result, k)=dict(w,m_pron) speek(k) result=unicode(result,'utf8') result=result.encode(enc) print result cleanup() if options.learnmode: try: wordlearn() except KeyboardInterrupt: print "" cleanup() except EOFError: print "" cleanup() cleanup() elif options.listall: wordlist() cleanup() if options.database == True: db=shelve.open(os.getenv("HOME")+"/.ydict.db","c") db.close() exit() while(1): try: word=raw_input(" ") except KeyboardInterrupt: print "" cleanup() except EOFError: print "" cleanup() (result,k)=dict(word,m_pron) speek(k) result=unicode(result,'utf8') result=result.encode(enc) print result if options.step == True: cleanup()

檢查是檔案還是資料夾

import os

os.path.isfile(filename)
os.path.isdir(folder)

取得圖檔大小


  1. 安裝PIL模組。  
  2. 加入下面程式碼。

from PIL import Image
 
# pick an image file you have in the working directory
# (or give full path name)
image_file = "D:\My Documents\My Pictures\Costa Rican Frog.jpg"
img = Image.open(image_file)
# get the image's width and height in pixels
width, height = img.size
print width
print height

列出資料夾下面的所有檔案

import os
li=[]
def listFiles(path):
    print path
    for name in os.listdir(path):
        if os.path.isdir(path+"\\"+name):# is folder
            listFiles(path+"\\"+name)
        else:
            li.append(path+"\\"+name)
    return li
print len(listFiles("D:\demo"))