프로그램 작성 중 다음과 같은 '[Decode error - output not utf-8]' 인코딩 관련 에러가 발생했을 때 해결책을 정리하려 합니다.


1. Sublime Text 2 에서 Preferences => Browse Packages.... 를 클릭합니다.


2. python 폴더에 들어 갑니다.

3. Python.sublime-build 파일을 엽니다.

4. cmd 창에서 chcp 명령어를 보고 활성 코드 페이지를 확인합니다.

5. 만약 활성 코드 페이지가 949 라면 Python.sublime-build 파일에 다음을 넣고 저장합니다.


Posted by ElvinKim
,

제목이 너무나 기네요. MySQLdb 모듈을 사용하여 INSERT 혹은 UPDATE를 실행한 뒤 에러가 없이 코드가 

실행 되었지만 DB 상에는 INSERT UPDATE 가 되지 않은 상태라면 DB Engine innoDB 인지 확인해 

봅니다. 만약 innoDB 가 맞다면 아래의 코드를 삽입합니다.


db 	= MySQLdb.connect(host="",user="",passwd="",db="")
db.autocommit(True)


autocommit(True)를 삽입하면 해결 될 것 입니다.

Posted by ElvinKim
,

python 에서 텍스트를 처리할 때 특수문자를 제거해야 할 때가 있습니다. 이럴 때 정규표현식 으로 처리할 수도 

있지만 다음과 같이 처리할 수도 있습니다.


sampleString = "1234567890abcdefgABCDEFG!@#$%^&*()_{}[]<>"
resultString = ""

for c in sampleString:
	if c.isalnum():
		resultString +=c

print resultString

결과는

1234567890abcdefgABCDEFG

[Finished in 0.2s]

Posted by ElvinKim
,

Python 에서 dictionary를 사용하다 보면 key 값의 존재 유무를 알아야 할 때가 있습니다.

예를 들어 [“a”, “b”, “c”, “c”, “a”, “a”, “b”, “b”, “a”, “a”, “a”, “a”] 같은 리스트에서 각각의 요소 개수를 

dictionary 로 관리 하고 싶을 때 각각의 카운트를 세야 하기 때문입니다. 물론 collections 같은 모듈을 사용할 

수도 있지만 dictionary 에 넣어야 하는 상황이라고 가정해 봅니다. 그럴 때 사용하는 것이 has_key 함수 입니

.


sampleDict ={"a":1 , "b":2}

print sampleDict.has_key("a")
print sampleDict.has_key("b")
print sampleDict.has_key("c")

결과는

True

True

False

[Finished in 0.2s]


그래서 위에 상황을 구현해 본다면

sampleList = ["a", "b", "c", "c", "a", "a", "b", "b", "a", "a", "a", "a"]
sampleDict = {}

for ele in sampleList:
	if sampleDict.has_key(ele):
		sampleDict[ele] += 1
	else :
		sampleDict[ele] = 1

print sampleDict


결과는

{'a': 7, 'c': 2, 'b': 3}

[Finished in 0.2s]

Posted by ElvinKim
,
sampleList= [1,2,3,4,5,6,1,2,3,4,5,6]

print list(set(sampleList))


결과 :

[1, 2, 3, 4, 5, 6]

[Finished in 0.2s]

Posted by ElvinKim
,
import re
print re.findall('[A-Z]{2,}', "ABCsidufapsoidfnDSSSSS")


결과 :

['ABC', 'DSSSSS']

[Finished in 0.2s]

Posted by ElvinKim
,

[Python] PyQt 튜토리얼

Python 2014. 10. 8. 16:55

python 과 Qt를 이용하여 GUI 프로그래밍하는 법을 알아보도록 하겠습니다.


python Qt를 이용하여 GUI 프로그래밍 하는 방법을 알아보도록 하겠습니다.


1. Qt를 설치 합니다.

http://www.qt.io/download/




파일 다운로드 한 후 인스톨을 완료 합니다.


2. PyQt4 를 설치합니다.

http://www.riverbankcomputing.co.uk/software/pyqt/download




파일을 다운로드 한 후 인스톨을 완료 합니다. 

3. Qt를 이용하여 레이아웃을 작성해 봅시다.




Designer 를 실행한 후 Widget을 생성 합니다.


Vertical Layout을 선택하여 올립니다.

Layout 을 클릭한 후 빈공간에 오른쪽 마우스 버튼을 누른 후 배치>수평으로 배치 를 누릅니다.

그 후 버튼을 드래그 하여 레이아웃 위에 올립니다.

버튼을 클릭한 후 objectName을 수정하거나 objectName이 무엇인지 확인 합니다.


그 후 ui를 저장합니다.

ui 파일이 있는 곳에서 pyuic4 -o 파이썬파일(사용자가 정함).py  UI파일.ui 을 실행 하면 파이썬 파일이 생성 됩니다.

참고) 만일 실해이 되지 않는다면 C:\Python27\Lib\site-packages\PyQt4 에 ui 파일을 저장하고 위 명령어를 사용하면 작동합니다.

 


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

# Form implementation generated from reading ui file 'test.ui'
#
# Created: Wed Oct 08 16:11:24 2014
#      by: PyQt4 UI code generator 4.9.6
#
# WARNING! All changes made in this file will be lost!

#coding!!
#=============================
import sys
#=============================

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Form(QtGui.QWidget): # Ui_Form(object) =>  Ui_Form(QtGui.QWidget):

    #coding!!
    #=============================
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setupUi(self)
    #=============================


    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(400, 300)
        self.horizontalLayout = QtGui.QHBoxLayout(Form)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.pushButton = QtGui.QPushButton(Form)
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.verticalLayout.addWidget(self.pushButton)
        self.horizontalLayout.addLayout(self.verticalLayout)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle(_translate("Form", "Form", None))
        self.pushButton.setText(_translate("Form", "PushButton", None))

    #coding!!
    #=============================
        self.pushButton.clicked.connect(self.printQt)        


    def printQt(self):
        print "hello Qt"
    #=============================

#coding!!
#=============================    
if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    ex = Ui_Form()
    ex.show()
    sys.exit(app.exec_())

#=============================    
    


주석 안에 있는 코드가 새로 넣은 코드 입니다.

위에 코드를 작성하고 저장한 뒤 파이썬 파일을 더블 클릭하면 실행됩니다.



Posted by ElvinKim
,

데이터 수집시에 파일을 같이 받아야 하는 상황이나 일괄적으로 파일을 다운로드할 필요가 있을 때 사용하면 용이하다.

import urllib

fileDownloader = urllib.URLopener()
fileDownloader.retrieve("download url", "save file path")


'Python' 카테고리의 다른 글

[python] 직접 만든 module import 시 import 한 클래스에 파일을 로드할 시 주의!  (0) 2014.10.20
[Python] PyQt 튜토리얼  (0) 2014.10.08
Crawler Class Sample  (0) 2014.09.25
List 필터링(Filtering)  (0) 2014.09.24
map function  (0) 2014.09.24
Posted by ElvinKim
,

Crawler Class Sample

Python 2014. 9. 25. 10:46

데이터 Crawling  시에 python 코드 샘플

#
# import modules
#
import MySQLdb
import urllib
import re


#
#URL
#
MAIN_URL = "http://www.test.com"

#
#TMPL
#
TMPL	= ""


#
# CLASS crawler
#
class Crawler(object):

	def __init__(self):

		self.db		    = MySQLdb.connect(host="",user="",passwd="",db="")
		self.cur  		= self.db.cursor()


	def __del__(self):
		self.db.close()
		

	def run(self):
        html  	= urllib.urlopen(MAIN_URL)
		page 	= html.read()
		match 			= re.compile(TMPL , re.DOTALL)
		match_list 		= match.findall(page)


if __name__ == "__main__":

	crawler = Crawler()
	crawler.run()



Posted by ElvinKim
,

List 필터링(Filtering)

Python 2014. 9. 24. 18:29

간단한 조건에 대하여 List 요소 필터링

(EX)

tmpList = range(1,101)
evenList = [num for num in tmpList if num%2 == 0]

'Python' 카테고리의 다른 글

[python] 직접 만든 module import 시 import 한 클래스에 파일을 로드할 시 주의!  (0) 2014.10.20
[Python] PyQt 튜토리얼  (0) 2014.10.08
[python]python file download  (0) 2014.09.25
Crawler Class Sample  (0) 2014.09.25
map function  (0) 2014.09.24
Posted by ElvinKim
,