The Eric, Python IDE

project/python 2012. 12. 11. 13:07

지금까지 PyScripter를 잘 사용해 오고 있었는데, 우연히 Eric이란 IDE 발견

 

http://eric-ide.python-projects.org/eric-screenshots.html 이런 기능을 하기 위해서 설치해야 할 것들이 좀 많은 것 같긴 하나, 아주 좋아 보임

 

그런데, 한글이 안 된다는 얘기도 있고...

 

http://blog.naver.com/dean3514/70125373162 Windows에 Eric 설치하기 (1)

http://blog.naver.com/dean3514/70125373439 Windows에 Eric 설치하기 (2)

http://blog.naver.com/dean3514/70125373602 Windows에 Eric 설치하기 (3)

http://blog.naver.com/dean3514/70125373728 Windows에 Eric 설치하기 (4)

Posted by trigger
,

PySwitch

project/python 2012. 10. 9. 21:56

Python으로 구현한 Switch 구문이 있음

 

http://stackoverflow.com/questions/5440990/is-there-any-value-to-a-switch-case-implementation-in-python 여기서 처음 그 존재 파악

 

http://pypi.python.org/pypi/pyswitch/1.2

http://code.activestate.com/pypm/pyswitch/

http://pydoc.net/pyswitch/1.2/test_pyswitch

 

http://efreedom.com/Question/1-4980146/Can-Combine-Switch-Case-Regex-Python Regex로 읽어온 것을 Switch해서 사용하는 방법

 

http://stackoverflow.com/questions/4614179/python-inline-elif-possible 초간단 사용 예

https://bitbucket.org/MatthewCox/bidbot/src/142c1735821e/Auction.py 실제 적용 사례

Posted by trigger
,

참고사항

 

http://docs.python.org/library/datetime.html

http://timebird.egloos.com/3362817

from datetime import date, timedelta

def date_add(number, base_date, sep="-"):
yy=int(base_date.split(sep)[0])
mm=int(base_date.split(sep)[1])
dd=int(base_date.split(sep)[2])
d=date(yy,mm,dd)
return d+timedelta(days=number)

 

http://codejob.co.kr/docs/page/67/

import datetime
def elapsed_time(sdate):
    e
= datetime.datetime.now()
   
if not sdate or len(sdate) < 14: return 0,0,0,0
    s
= datetime.datetime(int(sdate[:4]), int(sdate[4:6]), int(sdate[6:8]),
       
int(sdate[8:10]), int(sdate[10:12]), int(sdate[12:14]))
    days
= (e-s).days
    sec
= (e-s).seconds
    hour
, sec = divmod(sec, 3600)
    minute
, sec = divmod(sec, 60)
   
return days, hour, minute, sec

 

http://code.p-ark.co.kr/80

#!/usr/bin/python
# -*- coding: cp949 -*-

from datetime import *
import os
import sys
import time


def mktime():
    # 년, 월, 일, 시, 분, 초, 0, 0, 0
    return time.mktime( (10, 8, 20, 10, 20, 30, 0, 0, 0) )

def timestamp(timestamp):
    lt = time.localtime(float(timestamp)) #튜플 형태로 반환됨
    return "%02d.%02d.%04d %02d:%02d:%02d" % (lt[2], lt[1], lt[0], lt[3], lt[4], lt[5])

def timedeltaEx(prev_day):       
    timestampVar = time.localtime(time.time()); #현재 시각 가져옴
   
    year = time.strftime('%Y', timestampVar);
    month = time.strftime('%m', timestampVar);
    day = time.strftime('%d', timestampVar); #년 월 일 분리
   
    #현재 시각 에서 날짜 계산할 날을 더하거나 뺄수 잇다.
    dt = datetime( int(year), int(month), int(day) ) - timedelta( prev_day );      
    return dt.strftime('%Y-%m-%d');
   

print mktime();
mktime_test = mktime(); #타임스템프 만들기
print "time now: %s" % ( timestamp(mktime_test) ) #타임스템프 출력
print timedeltaEx(1) # 하루전의 날짜를 가져오기
#결과
#1282267230.0
#time now: 20.08.2010 10:20:30
#2010-08-19

 

내가 만든 것

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

from datetime import date, datetime, timedelta

def date_delta(base_date):
    yy=int(base_date[:4])
    mm=int(base_date[5:7])
    dd=int(base_date[8:10])
    d=datetime.date(yy,mm,dd)
    return (datetime.date.today() - d).days


base_date = "2012-07-02"

print date_delta(base_date)

 

if date_delta(base_date) < 7 :
    print "Yes! it works"
else :
    print "No, it doesn't work"

Posted by trigger
,
Posted by trigger
,
Posted by trigger
,

python + Excel

project/python 2010. 7. 4. 20:35

파이썬으로 daum의 wisefn 자료를 읽어다가 excel에 쓰는 방식으로 해보자

http://www.python-excel.org/

http://sourceforge.net/projects/pyxlwriter/
http://sourceforge.net/projects/pyexcelerator/ 이것이 위의 것을 이어서 개발된 모듈
http://gauryan.tistory.com/18 여기에서 보면 xlwt가 가장 활발하다는데...

xlwt 사용법
http://scienceoss.com/write-excel-files-with-python-using-xlwt/
https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/examples/ 예제

pyExcelerator 사용법
http://ntalikeris.blogspot.com/2007/10/create-excel-file-with-python-my-sort.html

pyExcelerator (xlwt) cheatsheet (create native Excel from pure python)
http://panela.blog-city.com/pyexcelerator_xlwt_cheatsheet_create_native_excel_from_pu.htm

내가 필요로 하는 기능

  • 기존에 있는 xls 파일에 원하는 부분에 써넣기
  • 예제 많을 것

cheatsheet.pdf

python-excel.pdf


예제
http://ppiazi.springnote.com/pages/4304681 한글
http://ppiazi.tistory.com/entry/xlwt-Excel-모듈
https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/examples/

http://ppiazi.tistory.com/33 

Posted by trigger
,
1. 준비사항
Python이 설치되어 있어야 함

2. Eclipse 설치
http://www.eclipse.org/ 에서 다운받아서 설치한다. 설치과정은 특별한 것은 없고, 압축을 푸는 것으로 완료

3. Eclipse > Help > Software updates


오른쪽의 Add site를 클릭하고

Location에 http://pydev.sourceforge.net/updates/ 를 입력한다

업데이트를 시키면 eclipse가 pydev와 관련된 zip 파일을 자동으로 다운로드 & 설치한다.

4. Window -> Preferences -> Pydev -> Interpreter - Python -> Python Interpreters 옆에 New 클릭

파이썬이 설치된 폴더의 Python.exe 선택


위의 과정대로 하면 다음과 같은 창이 뜬다. 이것으로 셋업 완료


Test 화면


5. 한글 언어팩 설치
설치한 Eclipse가 3.4 이상의 버전이라면 다음과 같이 온라인으로 설치한다. Help의 Software Updates를 누른다


두번째 탭의 Available Software를 선택하고, Add Site를 누르고, http://download.eclipse.org/technology/babel/update-site/ganymede 를 입력한다.


Pending이라고 나오는데 좀 기다리면 언어팩 리스트가 뜨고 Korean을 선택한다


Eclipse를 재시작하라고 나온다. 변경된 것을 적용하려면 재시작해야 한다.


다음과 같이 한글화된 메뉴로 보인다.


소스코드내의 한글이 문제되는 경우

소스코드내에 한글이 있을 경우, 다음과 같은 에러 메시지가 뜬다.

SyntaxError: Non-ASCII character "blah blah..."

이 때는, 소스코드 제일 윗줄에 다음과 같이 입력한다

#-*- coding: euc-kr -*-

그리고, 메뉴 -> Window -> Preferences -> Workspace -> Text file encoding을 Other로 선택한후 combo box에 EUC-KR을 직접 타이핑해서 입력한다.


Posted by trigger
,
Posted by trigger
,
서툰 목수의 연장탓

현재는 주로 PyScripter를 이용하고 있는데, 아직은 wxPython을 이용하고 있지 않아서이다. 디버깅을 하다가 기능이 좀 부족한 듯 싶어서 검색해 보니 다음과 같은 비교 리뷰가 있다.

A review of 6 Python IDEs
http://spyced.blogspot.com/2006/02/pycon-python-ide-review.html
http://spyced.blogspot.com/2005/09/review-of-6-python-ides.html

이 외에 또 다른 디버거로 다음과 같은 것이 있다.

Winpdb - A Platform Independent Python Debugger
http://winpdb.org/2008/04/a-call-for-contributions/
시험삼아 써보니 제법 괜찮은 듯. 에러 메시지가 좀 더 충실하게 나온다.

Posted by trigger
,

Farpy
http://farpy.holev.com/index.php 

PythonCard
http://pythoncard.sourceforge.net/ 
http://network.hanb.co.kr/view.php?bi_id=514 약간의 한글 설명
http://pythoncard.sourceforge.net/documentation.html 공식 document

wxDesigner
http://www.roebling.de 유료이다. 대부분의 평은 이것이 꽤 좋다고 말하고 있다.
http://www.cae.tntech.edu/help/programming/wxdesigner-getting-started/view wxDesigner Turotial

SPE
http://stani.be/python/spe/blog/ 
설치기 http://withrobot.tistory.com/160

VisualWX
http://visualwx.altervista.org/ 
http://visualwx.altervista.org/tutorial.php 튜토리얼. 플래쉬로 된 튜토리얼이 있음

wxGlade
http://wxglade.sourceforge.net/ wxGlade
wxGlade는 완전한 GUI 통합 개발환경이 아니라 화면에 보여지는 것만을 만들어준다.
완전한 통합 GUI 개발환경을 원한다면, Boa Constructor나 PythonCard가 좋을 것이다.
http://wiki.kldp.org/wiki.php/Wxglade-Tutorial 한글 wxGlade 튜토리얼
http://bebop.emstone.com/research/python/wxglade_eclipse/ 이클립스와 사용하는 방법

Boa Constructor
http://blog.bagesoft.com/entry/python-wxPython-GUI-boa-IDE-%EC%84%A4%EC%B9%98 
설명1 http://bebop.emstone.com/research/python/boa_constructor_tutorial/
설명2 http://freesearch.pe.kr/236?TSSESSIONfreesearchpekr=5ae5b40e71530e8c5af7abbe7c4a2da4 
간단한 사용설명서 http://www.superuser.co.kr/home/lecture/index.php?cateNo=4&secNo=10635

PAGE - Python Automatic GUI Generator
http://page.sourceforge.net/
http://sourceforge.net/projects/page


위의 몇가지 것들을 비교한 한국 파이썬 마을의 글
http://bbs.python.or.kr/viewtopic.php?p=38622&sid=83ea4e4ca36b06321fa45a065f4bb6a3

Posted by trigger
,

Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114644

import time
import threading

class Task( threading.Thread ):
    def __init__( self, action, loopdelay, initdelay ):
        self._action = action
        self._loopdelay = loopdelay
        self._initdelay = initdelay
        self._running = 1
        threading.Thread.__init__( self )

    def __repr__( self ):
        return '%s %s %s' % (
            self._action, self._loopdelay, self._initdelay )

    def run( self ):
        if self._initdelay:
            time.sleep( self._initdelay )
        self._runtime = time.time()
        while self._running:
            start = time.time()
            self._action()
            self._runtime += self._loopdelay
            time.sleep( self._runtime - start )

    def stop( self ):
        self._running = 0
   
class Scheduler:
    def __init__( self ):
        self._tasks = []
       
    def __repr__( self ):
        rep = ''
        for task in self._tasks:
            rep += '%s\n' % `task`
        return rep
       
    def AddTask( self, action, loopdelay, initdelay = 0 ):
        task = Task( action, loopdelay, initdelay )
        self._tasks.append( task )
   
    def StartAllTasks( self ):
        for task in self._tasks:
            task.start()
   
    def StopAllTasks( self ):
        for task in self._tasks:
            print 'Stopping task', task
            task.stop()
            task.join()
            print 'Stopped'

if __name__ == '__main__':

    def timestamp( s ):
        print '%.2f : %s' % ( time.time(), s )
   
    def Task1():
        timestamp( 'Task1' )

    def Task2():
        timestamp( '\tTask2' )

    def Task3():
        timestamp( '\t\tTask3' )
   
    s = Scheduler()

    #           task    loopdelay   initdelay
    # ---------------------------------------
    s.AddTask(  Task1,  1.0,        0       )
    s.AddTask(  Task2,  0.5,        0.25    )
    s.AddTask(  Task3,  0.1,        0.05    )

    print s
    s.StartAllTasks()
    raw_input()
    s.StopAllTasks()
Posted by trigger
,

며칠이나 골치 썩이던, 웹페이지에서 한글을 읽어다가 MySQL에 쓰는 문제를 완료.

출처: http://python.kr/viewtopic.php?p=57995&sid=64c9286c1a9876783aa4569c3047539a

※ python code에서의 세팅

           1. encoding: utf8
           2. DB를 연결한 후에 다음의 코드로 글자와 관련된 세팅을 확인

conn.query("set character_set_connection=utf8;")
conn.query("set character_set_server=utf8;")
conn.query("set character_set_client=utf8;")
conn.query("set character_set_results=utf8;")
conn.query("set character_set_database=utf8;")


※ MySQL의 character 세팅


           1. Config Wizard에서 utf8로 세팅

Example code

#-*- coding: utf8 -*-
#import urllib
#import BeautifulSoup
from BeautifulSoup import BeautifulSoup
import MySQLdb
import urllib2

#url = 'http://weather.local.naver.com/AreaCityWeather.nhn?m=subsi&fct=11H20301'
page=urllib2.urlopen("http://weather.local.naver.com/AreaCityWeather.nhn?m=subsi&fct=11H20301")
params = []

#soup = BeautifulSoup.BeautifulSoup( urllib.urlopen(url).read() )
soup = BeautifulSoup(page, fromEncoding="utf8")

inc1 = soup('table', {'width':'593', 'style':'border:1px solid #DCDDE0'})[0]
days = [inc2.contents[0] for inc2 in inc1('span', {'class':'gray01 b'})]
states = [inc2.contents[0] for inc2 in inc1('td', {'class':'gray01 ls'})]
params.extend( zip(days, states) )

for inc1 in soup('table', {'width':'117',}):
   day = inc1('span', {'class':'gray01 b'})[0].contents[0]
   state = inc1('td', {'height':'25', 'class':'gray01 ls'})[0].contents[0]
   params.append( (day, state) )

#print params
conn = MySQLdb.connect(host='localhost', db='weather', user='????', passwd='????')

#DB를 연결한 후에, 반드시 다음의 다섯줄을 추가해 주어야 한다
conn.query("set character_set_connection=utf8;")
conn.query("set character_set_server=utf8;")
conn.query("set character_set_client=utf8;")
conn.query("set character_set_results=utf8;")
conn.query("set character_set_database=utf8;")

#cursor = conn.cursor()
#db_info = {'host':'localhost', 'db':'weather', 'user':'root', 'passwd':'????', 'encoding': 'utf8',}
#conn = MySQLdb.connect(**db_info)
cursor = conn.cursor()
cursor.execute ("DROP TABLE IF EXISTS data")
cursor.execute ("""CREATE TABLE data(day VARCHAR(10),state VARCHAR(50))""")

for inc in params:
   query = ( "INSERT INTO data(day, state) VALUES('%s', '%s')" % inc )
#   query = ("INSER INTO data VALUES('%s','%s')"%inc)
   print query
#   cursor.execute(uery)
   cursor.execute( query.encode('utf8'))
   cursor.execute('COMMIT')

#   cursor.execute('''INSER INTO data VALUES('%s','%s')'''%inc)
   result=cursor.fetchall()
   print result
cursor.close()


만약 캐릭터셋이 euckr이나 Latin1이라면 DB 접속후에

conn.query("set character_set_connection=euckr;")
conn.query("set character_set_server=euckr;")
conn.query("set character_set_client=euckr;")
conn.query("set character_set_results=euckr;")
conn.query("set character_set_database=euckr;")

그리고, my.ini 파일에서

[mysqld]
character-set-client-handshake = FALSE
로 해버리면 한글이 잘 될 수도 있다.

Posted by trigger
,

Calendar Arithmetic (Python)
http://www.daniweb.com/code/snippet236.html

Plotting with Pylab
http://www.daniweb.com/code/snippet691.html

Using wxPython for Plotting
http://www.daniweb.com/code/snippet689.html

Read PDF Files with wxPython
http://www.daniweb.com/code/snippet618.html

Draw a Bar Graph (Python)
http://www.daniweb.com/code/snippet583.html
Modified version
http://www.goldb.org/goldblog/2007/09/26/PythonTkGraphExample.aspx

Plotting a Line Curve (Python)
http://www.daniweb.com/code/snippet578.html

Search File for Text and Copy
http://www.daniweb.com/code/snippet529.html

Limited Search for File
http://www.daniweb.com/code/snippet528.html

Full Search for File
http://www.daniweb.com/code/snippet527.html

wxPython Button Demo
http://www.daniweb.com/code/snippet502.html

Using Py2Exe (Python)
http://www.daniweb.com/code/snippet499.html

Sorting Algorithms in Python
http://www.daniweb.com/code/snippet452.html

wxPython ComboBox Demo
http://www.daniweb.com/code/snippet410.html

wxPython DrawRectangle Experiment
http://www.daniweb.com/code/snippet407.html

wxPython Slider Experiment
http://www.daniweb.com/code/snippet403.html

wxPython Mouse Position
http://www.daniweb.com/code/snippet401.html

Searching Text (Python)
http://www.daniweb.com/code/snippet392.html

File Handling with Python
http://www.daniweb.com/code/snippet389.html

Experimenting with For Loops (Python)
http://www.daniweb.com/code/snippet386.html

Testing the Psyco Module to Speed Up Python
http://www.daniweb.com/code/snippet369.html

Tinkering with Color (Python)
http://www.daniweb.com/code/snippet307.html

Experimenting with Python Class
http://www.daniweb.com/code/snippet287.html

Sort an Inventory List (Python)
http://www.daniweb.com/code/snippet256.html

wxPython ListBox Demo
http://www.daniweb.com/code/snippet227.html

Experimenting with Sets (Python)
http://www.daniweb.com/code/snippet219.html

Date and Time handling in Python
http://www.daniweb.com/code/snippet218.html

Simple Windows GUI Calculator (Python)
http://www.daniweb.com/code/snippet210.html

Experimenting with Lists (Python)
http://www.daniweb.com/code/snippet204.html

Experimenting with Dictionaries (Python)
http://www.daniweb.com/code/snippet192.html

Experimenting with Strings (Python)
http://www.daniweb.com/code/snippet162.html

PDF to Text
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/511465

Posted by trigger
,

xlrd 연습

project/python 2007. 8. 25. 18:41

주어진 엑셀 파일에서 종목코드 및 특정 셀의 값을 읽어서 매개변수로 사용하는 방법

# coding: utf-8
# *-* coding: utf-8 -*-
# -- coding cp949 --
import xlrd, time
book = xlrd.open_workbook("C:\Python25\getting_started\myfile.xls")
print "The number of worksheets is", book.nsheets   #sheet의 갯수

print "Worksheet name(s):", book.sheet_names()

sh = book.sheet_by_index(0)
#sh = book.sheet_by_name("test")    #index로만 하면 sheet의 이름을 마음대로 쓰지 못하니까 이것으로 하는 것이 더 좋다
#print sh.cell_type(0, 0)
#print sh.cell_type(0, 1)
#print sh.cell_type(0, 2)
#print sh.cell_type(1, 0)
#print sh.cell_type(1, 1)
#print sh.cell_type(1, 2)
#print sh.cell_type(2, 0)
#print sh.cell_type(2, 1)
#print sh.cell_type(2, 2)

print "_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/"

#print sh.cell_value(0, 0)
#print sh.cell_value(0, 1)
#print sh.cell_value(0, 2)
#print sh.cell_value(1, 0)
#print sh.cell_value(1, 1)
#print sh.cell_value(1, 2)
#print sh.cell_value(2, 0)
#print sh.cell_value(2, 1)
#print sh.cell_value(2, 2)

print "_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/"

#print sh.col(0)
print "_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/"

#print sh.col_slice(0, start_rowx=1, end_rowx=100)

#print sh.name, sh.nrows, sh.ncols
#print sh.row(2)
#print sh.col(0)
startcol = 7
endcol = 10
print sh.col_slice(0, startcol, endcol)

sh2 = book.sheet_by_index(1)
start = int(sh2.cell_value(0, 0))   #읽어오는 셀의 값에 int()를 씌워버렸더니 그냥 integer로 인식
end = int(sh2.cell_value(1, 0))   #읽어오는 셀의 값에 int()를 씌워버렸더니 그냥 integer로 인식
#print start
#print end
print sh.col_slice(0, start, end)

#print sh.row_types(2)
#print sh.row_values(2)
print "Cell D30 is", sh.cell_value(rowx=29, colx=3)
t = time.time()

#for rx in range(sh.nrows):
#    print sh.row(rx)
#for rx in range(sh.ncols):
#    print sh.col(rx)
print 'Python Elapsed %.02f' % (time.time() - t)

Posted by trigger
,

xlrd 주요 내용

project/python 2007. 8. 25. 17:06
Book Class

nsheets: worksheet의 갯수

sheet_by_index(sheetx)

       sheetx: sheet1의 경우에는 0, sheet2의 경우는 1. 이런 식으로 사용
       Returns: 특정 sheet를 선택

sheet_by_name(sheet_name)
       sheet_name: "시트네임" 이런 식으로 사용
       Returns: 특정 sheet를 선택

sheet_names()
       Returns: 시트의 이름들

Sheet Class

Sheet: sheet속의 모든 데이타. 그러나 이 클래스를 직접 불러서 쓸 일은 없고, xlrd.open_workbook("myfile.xls")와 같이 workbook을 읽어와서 sheet_by_index나 sheet_by_name으로 선택한다

Cell(ctype, value): type과 value로 이루어져 있고, 직접 이 클래스를 불러서 쓰진 않는다

cell_type(rowx, colx): cell_type(3, 4) 이런 식으로 쓰며, 셀에 있는 데이타의 type을 반환

cell_value(rowx, colx): cell_type(3, 4) 이런 식으로 쓰며, 셀에 있는 데이타의 value를 반환

col(colx): 예를 들어 보면, 한 칼럼에 있는 전체 내용을 반환한다.

[text:u'Symbol', text:u'A057330', text:u'A038500', text:u'A004870', text:u'A032580', text:u'A047600', text:u'A036420', text:u'A053070', text:u'A017170', text:u'A051530', text:u'A032820', text:u'A053170', text:u'A058550', text:u'A041940' 이런 식으로

row(rowx): 예를 들어 보면, 한 행에 있는 전체 내용을 반환한다.

col_slice(colx, start_rowx=0, end_rowx=None): start_rowx와 end_rowx를 직접 써 넣어서 특정칼럼의 특정부분만 잘라낸다(slice). end_rowx에서 숫자를 안 쓰고 None으로 해도 작동한다. 이 경우에는 내용이 있는 cell까지 계속해서 데이타를 읽어 들인다
row_slice(rowx, start_colx=0, end_colx=None): 위와 같고 행이라는 것만 차이점

name: sheet의 이름

ncols: number of cols(빈 칸이 아닌 내용이 있는 칼럼)
nrows: number of rows(빈 칸이 아닌 내용이 있는 행)

row_types(rowx): 특정 row의 type(cell type과 같은 형태)
row_values(rowx): 특정 row의 값

_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/

row_slice(rowx, start_colx=0, end_colx=None)를 이용하면 종목코드를 원하는 부분만 읽어올 수 있다
Posted by trigger
,
http://home.paran.com/johnsonj/hangul/How%20to%20Use%20UTF-8%20with%20Python.html 에서 답을 찾을 수 있다.

바이트 순서 표식자(Byte Order Marker (BOM))

UTF-8 파일은 가끔 바이트 순서 표식(BOM)으로 시작하여 UTF-8로 인코딩 되어 있음을 알린다. 이는 보통 윈도우즈에서 사용된다. Mac OS X에서, (예, TextEdit 같은) 어플리케이션은 BOM을 무시하고 파일이 다시 저장될 때 그 표식을 제거한다. W3C HTML 평가기는 구형 어플리케이션에서 BOM을 처리하지 못할 수도 있다고 경고한다. 유니코드는 효과적으로 그 표식을 무시하므로, 파일을 읽을 때 문제가 되지 않을 것이다. 파일의 시작에 이 표식을 추가해 ASCII로 인코딩되었는지 UTF-8로 인코딩되었는지 결정하고 싶다면, codecs 모듈은 이렇게 하기 위한 상수를 제공한다:

out = file( "someFile", "w" )
out.write( codecs.BOM_UTF8 )
out.write( unicodeString.encode( "utf-8" ) )
out.close()

BOM과 UTF-8을 사용할 때 주의할 필요가 있다. 솔직히, 나는 이것이 파이썬의 버그라고 생각하지만, 나도 잘 모른다. 파이썬은 BOM 값을 무시하는 대신에 유니코드 문자로 바꾼다. 예를 들어 (파이썬 2.3에서 테스트함):

>>> codecs.BOM_UTF16.decode( "utf16" )
u''
>>> codecs.BOM_UTF8.decode( "utf8" )
u'\ufeff'

UTF-16에 대하여, 파이썬은 BOM을 빈 문자열로 디코드하지만, UTF-8에 대해서는, 문자 하나로 디코드한다. 왜 차이가 있는가? UTF-8 디코더는 UTF-16 디코더와 똑 같은 일을 해야 당연하고 BOM 표식을 제거해야 할 것이다. 그렇지만, 그렇게 하지 않기 때문에, 다음과 같이 손수 탐지하여 제거할 필요가 있을 것이다:

import codecs
if s.beginswith( codecs.BOM_UTF8 ):
	# 바이트 문자열이 BOM과 함께 시작한다: 무언가를 한다.
	# 예를 들어, 문자열을 UTF-8로 디코드한다
	
if u[0] == unicode( codecs.BOM_UTF8, "utf8" ):
	# 유니코드 문자열이 BOM으로 시작한다: 무언가를 한다.
	# 예를 들어, 그 문자를 제거한다.

# BOM이 존재한다면, 유니코드 문자열의 선두로부터 걷어낸다. 
u.lstrip( unicode( codecs.BOM_UTF8, "utf8" ) )
Posted by trigger
,

파이썬 리소스

project/python 2007. 8. 14. 14:19

http://www.python.jp/Zope/
- 일본 파이썬 포럼. 일본어 번역기를 이용하면 많은 내용을 볼 수 있다.

http://home.paran.com/johnsonj/
- 파이썬 문서고

http://wiki.wxpython.org/index.cgi/AnotherTutorial
- 파이썬 WXTutorial

http://tdd.or.kr/wiki 
- 점프 투 파이썬의 인터넷 공개 버젼

Posted by trigger
,

http://openlook.org/blog/1159 에서 가져온 것을 해석하는 중

중간의 일부를 바꾸어서 내가 읽어오고자 하는 곳에 맞게 변경

def safeunicode(s):
    s = str(s).decode('utf-8')
    try:
        return s.encode('euc-kr').decode('cp949')
    except UnicodeDecodeError:
        return s

위에서 encode('latin-1')으로 되어 있는 것을 encode('euc-kr')으로 바꾸었더니 최소한 pyScripter에서는 한글 출력이 잘 되고 있다.

Test용 스크립트
from kaistfood import *
menu = getmenu(u'동측')
print ', '.join(menu[0])
menu = getmenu(u'서측')
print ', '.join(menu[0])

결과
모닝빵, 딸기잼, 크림스프, 양배추샐러드, 사우전, 토마토, 쌀밥, 두부된장국, 양송이야채볶음, 부추무침, 배추김치
쌀밥, 쇠고기무국, 계란찜, 시금치나물, 알타리김치

한글 처리시 주의사항: pyScripter에서 Edit > File Format > UTF-8 로 해줘야 에러가 생기지 않는다

Posted by trigger
,

공식 문서: 2.6 version
http://docs.python.org/index.html

Python 2.5 Quick Reference
http://rgruet.free.fr/PQR25/PQR2.5.html

Python 2.4 Quick Reference
http://rgruet.free.fr/PQR24/PQR2.4.html

파이썬 문서고
http://coreapython.hosting.paran.com/pygnudoc.html

파이썬 FAQ
http://coffeenix.net/doc/language/pyfaq/index.htm

파이썬 간편 참조서 2.3
http://onionmixer.net/~onion/python.pdf

파이썬 2.3 간편 참조서
http://codelog.tistory.com/15

JumpToPython
http://tdd.or.kr/pf/book/render_page?pagename=JumpToPython&keyword=&filename=&curpage=&historyname=&content=&newJump%20To%20Python

Jump to Python 2nd Edition
http://wikidocs.net/mybook/read/page?pageid=1

PDF 파일들로 설명이 되어 있다. dict의 has_key라는 것이 뭔지를 찾다가 발견한 사이트
http://sparcs.kaist.ac.kr/~wafe/doc/python/

블로그에 올려진 열혈강의 파이썬
http://creaplz.tistory.com/tag/Python

How to Think Like a (Python) Programmer
http://www.scribd.com/doc/2090074/How-to-Think-Like-a-Python-Programmer

Python : 2.4 version
IDE      : pyScript
기타 모듈 : Beautiful Soup, xlrd, pyExcelerator-0.6.3a

xlrd를 사용해서 파이썬에서 엑셀을 읽어오도록 한다

C:\Python24\Lib\site-packages\xlrd\doc\xlrd.html 를 해석해서 적용해야 엑셀을 이용할 수 있다.
http://www.lexicon.net/sjmachin/xlrd.htm
http://www.lexicon.net/sjmachin/README.html  설명

http://sourceforge.net/projects/pyexcelerator

Excel을 읽는 데는 xlrd가 뛰어나지만, Excel을 쓰는 용도로는 pyExcelerator가 더 뛰어나다고 한다 http://www.thescripts.com/forum/thread471698.html

내게 필요한 정도의 짧은 것들만 되어 있어서 이걸 그냥 써도 될 듯 하다
Easy Cross Platform Excel Parsing With Xlrd
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483742

Posted by trigger
,
http://pylab.tistory.com/3 에서 퍼옴. 그런데 저 사이트가 열리지 않는 문제가 있음

파이썬의 IDE 로 급부상하고 있는 PyScripter!
예쁘기도 하고 기능도 막강하고 해서 애용하는 분들이 많을 겁니다.

사용자 삽입 이미지

그런데 쓰다 보면 아래와 같이 UnicodeDecodeError 가 발생해서 PyScripter 가 먹통이 될 때가 있습니다.

사용자 삽입 이미지

OK 를 누르면 계속 디버깅 상태로 머물고 디버깅 상태에서 벗어날 수가 없게 됩니다.

사용자 삽입 이미지

이 것은 PyScripter 가 가지고 있는 Python Path 에 한글이 포함되어 있기 때문에 발생하는
문제입니다. 아래 메뉴로 들어가서 확인해 봅시다.

사용자 삽입 이미지

'바탕화면'이라는 한글이 포함되어 있네요.

사용자 삽입 이미지

저 Path 를 Remove 버튼을 눌러서 삭제해 주면 되지만 PyScripter 를 다시 실행시키면 저 Path 가 다시 입력 되어 있어서 매번 실행할 때마다 지워줘야 하는 불편함이 있습니다.

이 문제를 해결하기 위한 방법은 간단합니다. 바탕화면의 PyScripter 바로가기의 속성을
선택합니다.

사용자 삽입 이미지

속성을 선택한 후 시작위치를 한글이 없는 곳으로 설정해 주세요. 저는 C:\Python24\ex 에다 예제를 작성하기 때문에 'C:\Python24\ex' 로 설정했습니다.

사용자 삽입 이미지

이제 다시 PyScripter 를 실행하면 아무 문제 없이 잘 될 것입니다^^
그러면 파이썬 여행 즐겁게 하세요!!
Posted by trigger
,