잘 쓰던 PyScripter가 Windows 7에서 한글이 잘 되지 않아, Spyder로 IDE 변경

PyScripter에서 한글이 깨져 보이는 문제는 이렇게 해결한다 -> http://trigger.tistory.com/1518


 

https://code.google.com/p/spyderlib/ --> Spyder는 Turn_ERR_ver20121012.py를 돌렸더니 끝까지 돌지 않고 중간에 멈춰 버리는 현상 발생하여 탈락 -> Aptana로 다시 변경


Aptana Studio 3라는 것도 있다

http://alexnetster.blogspot.kr/2012/08/aptana-studio.html

http://cherryopatra.tistory.com/86

http://blackturtle.tistory.com/711663

 

Aptana Studio 설명서 http://it-ebooks.info/book/1836/ Aptana Studio Beginner's Guide


Aptana로 새로운 프로젝트를 만들고 Run하는 방법


1. 새로운 프로젝트 등록


http://pydev.org/manual_101_project_conf.html


http://krksap.tistory.com/entry/Python%EC%9C%BC%EB%A1%9C-%EB%86%80%EC%95%84%EB%B3%B4%EC%9E%90-02-HelloWorld%EB%A5%BC-%EC%B6%9C%EB%A0%A5%ED%95%B4%EB%B3%B4%EC%9E%90 한글


2. Interpreter 설정: Unresolved import error 문제

http://pydev.org/manual_101_interpreter.html



aptana 사용법 동영상 

http://www.youtube.com/watch?v=PI-vtnVPdhU

http://www.youtube.com/watch?v=XtnfY2cBbMA

http://pydev.org/manual_101_root.html


http://www.codeigniter-kr.org/tip/view/911 자동완성 기능 까는 법이 있음


Run하는 방법 중 가장 비슷해 보이는 것



http://pydev.org/manual_101_root.html 영문



모듈을 새로 설치하면 새로 설정해 줄 필요가 있을 것 같다. 


그 외 수많은 다른 Python editor 비교글

http://wiki.python.org/moin/PythonEditors

 

 

제일 밑의 테이블을 보면 GUI까지 같이 할 수 있는 에디터도 소개되어 있음

http://wiki.python.org/moin/IntegratedDevelopmentEnvironments

Monkey studio가 좋아 보인다

 

http://code.google.com/p/monkeystudio/

 

https://code.google.com/p/pythonxy/ 이것도 유용해 보임

http://pythonxynews.blogspot.kr/



이제는 PyScripter에만 매여있지 말고, 다른 에디터를 써보자


Visual Studio + Pytools http://pytools.codeplex.com/  그런데 이것은 CPython, IronPython만 지원한다


이것은 reverse engineering 툴이라는데...

http://oldresources.visual-paradigm.com/vpsuite3.1/instant_reverse_python.html



 

그 외의 다른 GUI IDE

http://jeez.eu/2009/10/29/integrated-development-environments-for-qt-and-not-only.html

 

 

KDE도 좋아 보임

http://www.kdevelop.org/screenshots

 

Zeus

http://www.zeusedit.com/lookmain.html

 

 

DRAKON Editor라는 것이 재미있어 보임 - 알고리즘을 그리는 에디터

http://drakon-editor.sourceforge.net/editor.html

DRAKON Editor에 대한 설명 http://noogabar.com/437

 

C++ python 바인더

http://sourceforge.net/projects/pygccxml/

Posted by trigger
,

https://code.google.com/p/shedskin/


그 외 다른 컨버터들

http://stackoverflow.com/questions/7112812/use-cython-as-python-to-c-converter

Posted by trigger
,

Google trends API

project/python 2012. 12. 16. 19:28

구글을 통한 종목 검색이 많아진다면, 사람들이 많이 찾아본다는 의미일 수 있음. 그렇지만 테마주는 제외해야 함

 

http://www.juiceanalytics.com/writing/programmatic-google-trends-api/

 

http://pypi.python.org/pypi/pyGTrends/0.81

Posted by trigger
,

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://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python

 

  1. http://code.activestate.com/recipes/410692/

  2. http://code.activestate.com/recipes/410695/

  3. http://code.activestate.com/recipes/181064/

 

테스트 해본 결과 - if elif를 사용한 switch는 여전히 느림

 

Dictionary를 쓰는 경우는 빠를 수는 있지만, 많은 경우의 dictionary를 정의하는 것은 무식한 방법임

다음의 lambda를 쓰거나 bisect를 쓰는 방법이 빠를 듯 함.

 

내가 원하는 해법이 들어 있음

http://stackoverflow.com/questions/2222859/python-dictionary-instead-of-switch-case

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
,

참고할 곳

http://coffeenix.net/doc/develop/Python_Regular_Expression_HOWTO.html 문법

http://serious-code.net/moin.cgi/PythonRegularExpression search, match 등의 사용법

 

http://flockhart.virtualave.net/RBIF0100/regexp.html Regular Expressions by Example

http://www.clear.rice.edu/comp200/12spring/notes/11/finger-re.shtml Python Regular Expressions “Finger Exercises”
http://code.google.com/intl/ko/edu/languages/google-python-class/regular-expressions.html 구글 파이썬 클래스의 Regular Expression

http://www.python-course.eu/re.php 그래픽한 설명

http://osl.iu.edu/~pgottsch/swc2/lec/re.html 

 

Regex builder

http://www.ultrapico.com/Expresso.htm 이것이 제일 좋다

http://renschler.net/RegexBuilder/

http://www.radsoftware.com.au/regexdesigner/

http://mac.softpedia.com/progDownload/Regex-Widget-Download-28467.html

http://www.regexbuddy.com/ 유료

 

 

Online Python Regular Expression Testing Tool
http://www.pythonregex.com/ 

http://re.dabase.com/ 관련된 다른 표현까지 다 보여줌. 가장 유용한 듯

http://re-try.appspot.com/ Builder 역할은 못 함

http://ksamuel.pythonanywhere.com/

 

Regular Expressions: 30 Useful Tools and Resources
http://www.hongkiat.com/blog/regular-expression-tools-resources/


 

http://social.msdn.microsoft.com/Forums/en-US/regexp/thread/12010a1e-4d77-404e-9bf3-d93c9797fdce
http://txt2re.com/

http://freecode.com/projects/pyreb

http://savannah.nongnu.org/projects/pyreb


http://gskinner.com/RegExr/  

http://kodos.sourceforge.net/home.html Kodos. 다운로드해서 사용하면 된다. 이것 저것 쓰다 보니 이걸 제일 많이 쓰게 된다.

http://www.pythonregex.com/ 온라인 Regex tool

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
,
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
,


발행회사 고유코드로 1993년 8월 30일을 기준으로 설립년도 순에 따라 00001부터 일련번호로 부여하고 그 후는 코드신청 순서에 따라 순차적으로 부여

주권종류코드 : 보통주 / 우선주 구분
단축코드의 경우는 보통주 0,  1우선주 5,  2우선주 7, ...

신주종류코드 : 구주 / 신주 구분
- 구주 0,  1신주 1,  2신주 2, ...

즉 0은 보통주, 5는 구형 우선주, 6,7,8 등은 신형 우선주, 1,2는 신주

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
,

Beautifulsoup으로 읽어온 숫자들은 파이썬 내부적으로는 모두 문자열로 처리된다. 실제로 계산을 하기 위해서는 숫자가 필요하기 때문에 다음과 같은 것을 이용해서 숫자로 처리하면 된다.

string.atof #이것은 string으로 읽어온 것을 float로 처리한다.
string.atoi #이것은 string으로 읽어온 것을 integer로 처리한다.

문자로 읽어올 때 12,345 같은 문자의 경우 중간의 쉼표를 제거해야 atof를 이용해서 제대로 숫자로 처리할 수 있는데 다음과 같은 간단한 함수를 이용하면 된다.

def normalize(s):
    if s == None:
        return 0
    elif s != None:
        return s.replace(',', '').strip()

위에서 replace(',', '') 를 replace(',', ' ') 로 하면 에러가 나니 주의

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
,