2018년 6월 29일 금요일

Python RE 2

import re
import statistics
import collections

data = []
f = open("localhost_access_log.2016-04-01.txt", "r" )
for l in f:
    match = re.search("^[\d:.]+", l )
    ip = match.group()

    match = re.search('\[([\w/:]+)', l)
    date = match.group(1)

    match = re.search(' /[\w.-]*', l)
    doc = match.group().strip()

    match = re.search('[\d-]+$', l)
    byte = match.group()
    if (byte == '-'):
        byte = 0    byte = int(byte)
    data.append([ip, date, doc, byte])
f.close()

print("1.전체 로그 출력")
for i in data:
    print("접속ip: {}\n접속일: {}\n요청문서: {}\n바이트크기: {}".format(i[0], i[1], i[2], i[3]))
    print("-"*30)

print("\n2. ip별 접속회수")
ip_list = [n[0] for n in data]
cip = collections.Counter(ip_list)
for i in cip:
   print(i, cip[i],"회")

print("\n3. 문서별 방문회수")
doc_list = [n[2] for n in data]
cdoc = collections.Counter(doc_list)
for i in cdoc:
   print(i, cdoc[i],"회")

print("\n4. 전체전송 바이트 사이즈, 평균 전송 바이트 사이즈, 전송 바이트 사이즈 표준 편차")
byte_list = [n[3] for n in data]
s = sum(byte_list)
m = statistics.mean(byte_list)
d = statistics.stdev(byte_list)
print("전체 전송 바이트 크기: {}\n평균 전송바이트 사이즈: {}\n전송 바이트 사이트 표준편차: {}".format(s,m,d))

print("\n5. 가장 많이 방문한 ip와 방문 회수")
m = cip.most_common(1)
m = m[0]
print(m[0], m[1], "회" )







import re
import collections
from statistics import mean, stdev
fp = open('localhost_access_log.2016-04-01.txt')
data = []
for rd in fp:
    match = re.search('([\d.:]+) \S+ \S+ \[([\w:/]+) \S+\] "\S+ (\S+) \S+" \d+ (\S+)', rd )
    d={}
    d['ip']= match.group(1)
    d['dt']= match.group(2)
    d['view']= match.group(3)
    bsize =  match.group(4)
    bsize = 0 if bsize=='-' else int(bsize)
    d['bsize']= bsize
    data.append( d )

# # 1. 전체 로그 출력# for dt in data:#     print("접속ip:", dt['ip'])#     print("접속일:", dt['dt'])#     print("요청문서:", dt['view'])#     print("바이트크기:", dt['bsize'])#     print("="*10)#2.ipList = [ n['ip'] for n in data]
ipCount = collections.Counter(ipList)
for ip,cnt in ipCount.items():
    print("ip:",ip,"접속횟수:",cnt)

#3.# viewList = [ n['view'] for n in data]# viewCount = collections.Counter(viewList)# for view,cnt in viewCount.items():#     print("페이지:",view,"접속횟수:",cnt)
#4.
print( "전체전송사이즈:", sum([n['bsize'] for n in data] ) )
print( "평균전송사이즈:", mean([n['bsize'] for n in data] ) )
print( "표준편차:", stdev([n['bsize'] for n in data] ) )

#5.mip,cnt  =  ipCount.most_common(1)[0]
print("가장많이 방문ip:", mip, "방문횟수:", cnt )

# print( data )
    # print("ip:", match.group(1) )    # print("dt:",match.group(2) )    # print("view:", match.group(3) )    # print("bsize:", match.group(4) )    # print("="*20)

2018년 6월 28일 목요일

Python PyQt5

PyQt5
pyqt5-tools


from PyQt5.QtWidgets import *
import sys # commandline args
def buttonClicked():
    print("clicked")

app = QApplication(sys.argv)  # Queue 메모리에서 이벤트를 가져 오기 위한 loop
dlg = QDialog()
dlg.setWindowTitle("Hi")
dlg.setGeometry(100, 100, 500, 300)
dlg.show()

layout = QVBoxLayout()
button = QPushButton("클릭")
button.clicked.connect(buttonClicked)
edit   = QLineEdit()

layout.addWidget(button)
layout.addWidget(edit)

dlg.setLayout(layout)

app.exec() # 무한 루프. Queue 메모리 체크print("end...")




from PyQt5.QtWidgets import *
import sys # commandline argsclass MyWindow:
    def __init__(self):
        self.dlg = QDialog()
        self.dlg.setWindowTitle("Hi")
        self.dlg.setGeometry(100, 100, 500, 300)
        self.dlg.show()

        self.layout = QVBoxLayout()
        self.button = QPushButton("클릭")
        self.button.clicked.connect(self.buttonClicked)
        self.edit   = QLineEdit()

        self.layout.addWidget(self.button)
        self.layout.addWidget(self.edit)
        
        self.dlg.setLayout(self.layout)

    def buttonClicked(self):
        print("clicked")

def main():
    app = QApplication(sys.argv)  # Queue 메모리에서 이벤트를 가져 오기 위한 loop    my = MyWindow()
    app.exec() # 무한 루프. Queue 메모리 체크    print("end...")

if __name__ == '__main__':
    main()




from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi # XML UI 정보를 로딩해서 객체를 생성해 줌.import sys

class MyWin:
    def __init__(self):
        self.dlg = loadUi("a.ui")
        self.dlg.show()

        self.dlg.pushButton.clicked.connect(self.buttonClicked)
        self.dlg.radioButton.toggled.connect(lambda : print("toggled"))


    def buttonClicked(self):
        print("clicked")
        # print(self.dlg.lineEdit.setText("dadsd")) # designer에 있는 속성에서 set과 속성 첫글자를 대문자로 바꿔주면 설정 함수이다.(대개)        print(self.dlg.lineEdit.text()) # designeer의 속성 이름에 ()를 붙여주면 값이 넘어 온다.
app = QApplication(sys.argv)
a = MyWin()
app.exec()





from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi # XML UI 정보를 로딩해서 객체를 생성해 줌.import sys

class MyWin:
    def __init__(self):
        self.dlg = loadUi("b.ui")
        self.dlg.show()

        self.dlg.pushButton.clicked.connect(self.buttonClicked)

    def buttonClicked(self):
        print("clicked")
        print(self.dlg.spinBox.value(), self.dlg.spinBox_2.value())
        s = self.dlg.spinBox.value()+self.dlg.spinBox_2.value();
        print(s)
        self.dlg.lineEdit.setText(str(s))

app = QApplication(sys.argv)
a = MyWin()
app.exec()




from PyQt5.QtWidgets import *
from PyQt5.uic import loadUi # XML UI 정보를 로딩해서 객체를 생성해 줌.import sys

class MyWin:
    def __init__(self):
        self.dlg = loadUi("d.ui")
        self.dlg.show()

        self.dlg.pushButton.clicked.connect(self.buttonClicked)
        self.init_widget()

    def init_widget(self):
        self.dlg.listWidget.addItems(['LG1', 'LG2', 'LG3', 'LG4'])
        self.dlg.listWidget.clicked.connect(self.buttonClicked)
        self.dlg.actionMenu2.triggered.connect(self.buttonClicked_menu2)

    def buttonClicked_menu2(self):
        print("buttonClicked_menu2")
        self.pop = loadUi("a.ui")
        #self.pop.show()# show는 modalless. exec는 모달로 구동 함.        self.pop.exec()
        print("hello") # exec로 실행한 경우, dlg가 닫혀야 이 라인이 실행된다.
    def buttonClicked(self):
        print("clicked")
        # print(self.dlg.spinBox.value(), self.dlg.spinBox_2.value())        # s = self.dlg.spinBox.value()+self.dlg.spinBox_2.value();        print(self.dlg.listWidget.currentItem().text())
        self.dlg.lineEdit.setText(self.dlg.listWidget.currentItem().text())

app = QApplication(sys.argv)
a = MyWin()
app.exec()





Python RE

반복 메타 문자 * + ? {} 는 그 앞글자가 몇번 나오는지 설정
match = re.search('ap*le', s1) # p가 0회 이상 반복 되는 것을 찾아 달라. OK : apple, appple, ale.match = re.search('ap+le', s1) # p가 1회 이상 반복 되는 것을 찾아 달라. OK : aple, apple, appple. NG : alematch = re.search("ap?le", s1) # p가 0 또는 1회. OK : ale, aple. NG : apple
match = re.search('ap{2}le', s1) # p가 2번만 반복된 것만 찾는다. OK :apple  NG : aple, appplematch = re.search('ap{2, 5}le', s1) # p가 2번, 또는 3번, 또는 4번 또는 5번 반복된 것만 찾는다. OK :apple, appple, apppple  NG : aple
매칭 메타 문자 . []
match = re.search('ki.i', s1) # .은 개행을 제외한 모든 문자를 허용. OK : kiwi ki3i kixi ki#i ki?i "ki i"   NG : ki\nimatch = re.search('^app', s1)  # ^은 문자열이 주어진 패턴으로 시작하면 매칭 됨. s1이 app로 시작한다면 찾음. NG : ^kiwimatch = re.search("nna$", s1) # $는 문자열이 주어진 패턴으로 끝나는지 확인. s1이 nna로 끝나면 찾음.
match = re.search('[abcxz]pple', s1) # []문자의 집합 중 한문자가 대신할 수 있다. OK : apple, bpple, cpple     NG : dpplematch = re.search('ki[vwx]i', s1) # []문자의 집합 중 한문자가 대신할 수 있다. OK : kiwi kiwwwwi kivwvwvwi    NG kiwwaxximatch = re.search('ki[a-z]i', s1) # []문자 범위   OK : kixi    NG : kiXimatch = re.search('ki[a-z]+i') # OK : kidaljdlkajdklajdlkalkji  NG : kikjklj2i kiWdsdai
match = re.search('서울[시은가]', s2) # OK 서울시 서울은 서울가 NG 서울이match = re.search('서울[가-힣]', s2)  # 모든 한글글자 1개  OK : 서울이 서울락 서울흘  NG: 서울2 서울s
match = re.search('ki[a-zA-Z0-9]+i') # OK : kiai kiZi ki0i    NG: ki#i ki?i
match = re.search('melon|banana') # melon 또는 banana면 됨.match = re.search('melon|ba+na') #
escape \d
match = re.search('ki\di') # ki[0-9]i와 같음. OK : ki0i ki1i ki2imatch = re.search('ki[\da-z]i') # ki[0-9a-z]i와 같음.match = re.search('ki[\da-z. ]') # OK: ki0. 찾아줌
Search는 첫번째 것만 찾아 줌. 매칭 되는 것 다 찾고자 하면 findAll을 써야 함. 그 결과는 list 객체.
match = re.search('app[a-z]+') # app, applicationsList = re.findall('app[a-z]+', s1)

[] 안의 ^은 not 의 의미 임. []밖과 다름.
\D는 [^0-9] 숫자가 아님을 의미

match = re.search('ki\Di')  # OK : ki#a  NG ki5i
\s 화이트 스페이스 (탭, 개행, 스페이스)
match = re.search('ki\si')  # OK : ki i, ki    i
\S 화이트 스페이스가 아닌 것
match = re.search('ki\Si')  # OK : kiwi ki#i ki9i
\w 숫자, 영어 대소문자, _
match = re.search('ki\wi') # ki_i kiwi kiWi ki9i
\W 숫자, 영어, 대소문자, _ 가 아닌 글자.

s3에서 숫자3개-소문자3개
match = re.search('\d{3}-[a-z]{3}', s3)

() 그룹
match = re.search('(\d{3})-([a-z]{3})', s3)
print(match.groups(), match.groups(1), match.groups(2) ,sep='\n')

print(match.group())


# []밖과 안에서 의미가 다른 문자들이 있다.# .는 []밖에서는 줄바꿈을 제외한 모든 문자. []안에서는 그냥 .이다. escape 안해 도 됨.# ^는 []밖에서는 시작점. []안에서 첫자리에 쓰이면 가령 [^OOO] 이면 OOO의 negation이다.
# group은 1번이 첫번째 그룹 괄호를 의미 함.
# ASCII에서 \b는 벨소리임. 그런데 정규식에서도 \b는 공백 escape 의미로 씀.# 때문에 ASCII 코드가 아니라, 정규식 \b 공백으로 하기 위해서는 매칭 앞에 r을 붙여줘야 한다.import re
s1 = "apple kiwi banana appple ale application"s2 = "서울시 은평구"s3 = "123-abc def-ghi jkl-23 566-Abc"s4 = '<a href="test.html"> <img src="my.jpg"> </a> <div> aaa</div>'s5 = 'abc$ 192.168.12.240 --  22^352 [01/Apr/2016:12:39:00 +0900] "GET /bg-middle.png HTTP/1.1" 200 1918's6 =  "aaa bbb.ccc.dd@aa.co.kr 123ffg my_test@my.co.kr"s8 = "sdsadPYTHON like"s9 = "abc\ng"s10 = '''python testprogram hello ppp aaaphone my'''s11 = 'abc#def ghi-jkl'
match = re.search('\d+.\d+.\d+.\d+', s5)
print(match.group())
s = re.sub('app\w+', 'like', s1) # 앞 패턴의 문자들을 뒤 문자열로 바꿔 줌print(s)

my = ['love', 'like', "like", "love"]
cnt = -1def fn(x):
    global cnt
    cnt += 1    return my[cnt]+x.group()

s = re.sub('app\w+', fn, s1)
print(s)

# 함수의 정적 변수 사용하는 방법def fn(x):
    fn.cnt += 1    return my[fn.cnt]+x.group()
fn.cnt = -1  # 함수 선언 밑에 초기 값을 적어 준다.
s = re.sub('app\w+', fn, s1)
print(s)

# match = re.search('href=\"(\w+.?\w+?)\"', s4)match = re.search('\[([\w/:]+)', s5)
match = re.search('GET /(\S+)', s5)
match = re.search('\d+$', s5)
ml = re.findall('[\d^]+', s5)
ml = re.findall('\w+$', s5)
print(ml)

match = re.search("pY", s8, re.I) # Ignore casematch = re.search("abc.g", s9, re.DOTALL) # .이 개행까지 대신할 수 있게 함.match = re.search(r"^p\w+\s+\w+", s10, re.M) # ^는 전체 문자열의 시작을 의미하지만, re.M을 추가하면 각 라인별 시작으로 바꿔 줌.
com = re.compile("app\w+")  # 같은 패턴을 다른 스트링에 적용하고자 할 때는 미리 컴파일 해 둔 것을 사용하면, 속도가 더 빠름.match = com.search(s1)

s = re.split("[# -]", s11) # 주어진 문자들로 스트링을 잘라 냄.print(s)

if match:
  print(match.group())
else:
  print("not found")

fi = re.finditer('app\w+', s1) # match 객체 generator를 돌려 줌.fi = re.finditer('(\S+)@\S+', s6) # match 객체 generator를 돌려 줌.ml = re.findall('(\S+)@\S+', s6) # match 객체 generator를 돌려 줌. 첫번째 항목의 group list를 돌려 줌.
for i in fi:
    print(i.group(1))

# if match:#   print(match.group())# else:#   print("not match")
# try:#     반복 메타 문자 * + ? {} 는 그 앞글자가 몇번 나오는지 설정#     match = re.search('ap*le', s1) # p가 0회 이상 반복 되는 것을 찾아 달라. OK : apple, appple, ale.#     match = re.search('ap+le', s1) # p가 1회 이상 반복 되는 것을 찾아 달라. OK : aple, apple, appple. NG : ale#     match = re.search("ap?le", s1) # p가 0 또는 1회. OK : ale, aple. NG : apple##     match = re.search('ap{2}le', s1) # p가 2번만 반복된 것만 찾는다. OK :apple  NG : aple, appple#     match = re.search('ap{2, 5}le', s1) # p가 2번, 또는 3번, 또는 4번 또는 5번 반복된 것만 찾는다. OK :apple, appple, apppple  NG : aple##     매칭 메타 문자 . []#     match = re.search('ki.i', s1) # .은 개행을 제외한 모든 문자를 허용. OK : kiwi ki3i kixi ki#i ki?i "ki i"   NG : ki\ni#     match = re.search('^app', s1)  # ^은 문자열이 주어진 패턴으로 시작하면 매칭 됨. s1이 app로 시작한다면 찾음. NG : ^kiwi#     match = re.search("nna$", s1) # $는 문자열이 주어진 패턴으로 끝나는지 확인. s1이 nna로 끝나면 찾음.##     match = re.search('[abcxz]pple', s1) # []문자의 집합 중 한문자가 대신할 수 있다. OK : apple, bpple, cpple     NG : dpple#     match = re.search('ki[vwx]i', s1) # []문자의 집합 중 한문자가 대신할 수 있다. OK : kiwi kiwwwwi kivwvwvwi    NG kiwwaxxi#     match = re.search('ki[a-z]i', s1) # []문자 범위   OK : kixi    NG : kiXi#     match = re.search('ki[a-z]+i') # OK : kidaljdlkajdklajdlkalkji  NG : kikjklj2i kiWdsdai##     match = re.search('서울[시은가]', s2) # OK 서울시 서울은 서울가 NG 서울이#     match = re.search('서울[가-힣]', s2)  # 모든 한글글자 1개  OK : 서울이 서울락 서울흘  NG: 서울2 서울s##     match = re.search('ki[a-zA-Z0-9]+i') # OK : kiai kiZi ki0i    NG: ki#i ki?i##     match = re.search('melon|banana') # melon 또는 banana면 됨.#     match = re.search('melon|ba+na') ###     escape \d#     match = re.search('ki\di') # ki[0-9]i와 같음. OK : ki0i ki1i ki2i#     match = re.search('ki[\da-z]i') # ki[0-9a-z]i와 같음.#     match = re.search('ki[\da-z. ]') # OK: ki0. 찾아줌##     Search는 첫번째 것만 찾아 줌. 매칭 되는 것 다 찾고자 하면 findAll을 써야 함. 그 결과는 list 객체.#     match = re.search('app[a-z]+') # appa, application#     sList = re.findall('app[a-z]+', s1)##     [] 안의 ^은 not 의 의미 임. []밖과 다름.#     \D는 [^0-9] 숫자가 아님을 의미##     match = re.search('ki\Di')  # OK : ki#a  NG ki5i##     \s 화이트 스페이스 (탭, 개행, 스페이스)#     match = re.search('ki\si')  # OK : ki i, ki    i##     \S 화이트 스페이스가 아닌 것#     match = re.search('ki\Si')  # OK : kiwi ki#i ki9i##     \w 숫자, 영어 대소문자, _#     match = re.search('ki\wi') # ki_i kiwi kiWi ki9i##     \W 숫자, 영어, 대소문자, _ 가 아닌 글자.##     s3에서 숫자3개-소문자3개#     match = re.search('\d{3}-[a-z]{3}', s3)##     () 그룹#     match = re.search('(\d{3})-([a-z]{3})', s3)#     print(match.groups(), match.groups(1), match.groups(2) ,sep='\n')##     print(match.group())#     #print(sList)# except Exception as err:#     print("not found")

2018년 6월 27일 수요일

Python C

https://docs.python.org/3/c-api/arg.html


#include "python.h"


static PyObject *
extest_circle(PyObject *self, PyObject *args)
{
int r;
int s;
if (!PyArg_ParseTuple(args, "i", &r)) // 매개변수 값을 분석하고 지역변수에 할당 시킵니다.
return NULL;
s = 3.141592*r*r;
return Py_BuildValue("i", s);  //python type conversion..
}

static PyObject *
extest_hap(PyObject *self, PyObject *args)
{
int a, b;
int sum;
if (!PyArg_ParseTuple(args, "ii", &a, &b)) // 매개변수 값을 분석하고 지역변수에 할당 시킵니다.
return NULL;
    sum = a + b;
return Py_BuildValue("i", sum);  //python type conversion..
}

static PyObject *
extest_strlen(PyObject *self, PyObject *args)
{
const char* str = NULL;
int len;
if (!PyArg_ParseTuple(args, "s", &str)) // 매개변수 값을 분석하고 지역변수에 할당 시킵니다.
return NULL;
len = strlen(str);
return Py_BuildValue("i", len);  //python type conversion..
}

static PyMethodDef extestMethods[] = {
{ "strlen", extest_strlen, METH_VARARGS, "count a string length." },
    { "hap", extest_hap, METH_VARARGS, "sum two" },
    { "circle", extest_circle, METH_VARARGS, "area of circle" },
    { NULL, NULL, 0, NULL } // 배열의 끝을 나타냅니다.
};

static struct PyModuleDef extestmodule = {
PyModuleDef_HEAD_INIT,
"extest",            // 모듈 이름
"It is test module.", // 모듈 설명을 적는 부분, 모듈의 __doc__에 저장됩니다.
-1,
extestMethods
};

PyMODINIT_FUNC
PyInit_extest(void)
{
return PyModule_Create(&extestmodule); // 공유 메모리 영역에 dll을 적재한다.
}

---------------------
import extest
n = extest.strlen("abc")
s = extest.hap(10, 20)
print(n, s)

print(extest.circle(10))



Python DB

관계형 DB

sqlite
maria db - 중형 DB 무료

자료
w3cschool SQL

sqlite3 권장은 매 execution 마다 connect / close 하는 것.

테이블 생성
import sqlite3

# connection은 DB가 존재하면, connect만 함.# DB가 없으면 생성하고 connect
# 표준 SQL에서 문자열은 무조건 single quote를 쓴다. '# 다만, execute의 파라미터로 튜플을 넘겨줄 때는 double도 상관 없음.
def createStudentTable():
    try:
        c = sqlite3.connect("my.db")
        sql = "create table if not exists student(name varchar(20), age int)"       
        c.execute(sql)
        c.commit() # 추가 수정 삭제은 commit을 불러줘야 함.        
        print("OK")
        c.close()
    except Exception as err:
        print(err)

def insertStudent(data):
    try:
        c = sqlite3.connect("my.db")
        sql = "insert into student (name, age) values (?,?)"      
        c.execute(sql, data)
        c.commit() # 추가 수정 삭제은 commit을 불러줘야 함.        
        print("OK")
        c.close()
    except Exception as err:
        print(err)

def insertStudentMany(data):
    try:
        c = sqlite3.connect("my.db")
        sql = "insert into student (name, age) values (?,?)"        
        c.executemany(sql, data)
        c.commit() # 추가 수정 삭제은 commit을 불러줘야 함.        
        print("OK")
        c.close()
    except Exception as err:
        print(err)

createStudentTable()
insertStudent(("이순신", 20))
insertStudentMany([("이순신", 20), ("홍길동", 30)])



데이터 Insert





import sqlite3

def createTable():
    try:
        c = sqlite3.connect("per.db")
        sql = "create table if not exists person (name varcahr(20), age int)"       
        c.execute(sql)
        c.commit()
        c.close()
    except Exception as err:
         print (err)

def insertRecord(data):
    try:
        c = sqlite3.connect("per.db")
        sql = "insert into person (name, age) values (?, ?)"        
        c.executemany(sql, data)
        c.commit()
        c.close()
    except Exception as err:
         print (err)

createTable()

data = []
while True:
    name = input("이름:")
    age = int(input("나이:"))
    data.append((name, age))
    yn = input("계속 입력 ? :")
    if (yn != 'y'):
        insertRecord(data)
        break



데이터 업데이트
import sqlite3

def createTable():
    try:
        c = sqlite3.connect("per.db")
        sql = "create table if not exists person (name varcahr(20), age int)"       
        c.execute(sql)
        c.commit()
        c.close()
    except Exception as err:
         print (err)

def updateData():
    try:
        c = sqlite3.connect("per.db")
        sql = "update person set name='김철수4', age=22 where name='김철수'"       
        c.execute(sql)
        c.commit()
        c.close()
        print("수정 성공")
    except Exception as err:
        print(err)

updateData()



동적 업데이트

import sqlite3

def createTable():
    try:
        c = sqlite3.connect("per.db")
        sql = "create table if not exists person (name varcahr(20), age int)"        
        c.execute(sql)
        c.commit()
        c.close()
    except Exception as err:
         print (err)

def updateData(name, new_name, new_age):
    try:
        c = sqlite3.connect("per.db")
        sql = "update person set name=?, age=? where name=?"        
        data = (new_name, new_age, name)
        c.execute(sql, data)
        c.commit()
        c.close()
        print("수정 성공")
    except Exception as err:
        print(err)

name = input("검색이름: ")
new_name = input("수정이름:")
new_age = int(input("수정 나이:"))
updateData(name, new_name, new_age)





삭제 하기
# deleteimport sqlite3

def createTable():
    try:
        c = sqlite3.connect("per.db")
        sql = "create table if not exists person (name varcahr(20), age int)"        c.execute(sql)
        c.commit()
        c.close()
    except Exception as err:
         print (err)

def deleteData(name):
    try:
        c = sqlite3.connect("per.db")
        sql = "delete from person where name=?"        
        data = (name,)
        c.execute(sql, data)
        c.commit()
        c.close()
        print("삭제 성공")
    except Exception as err:
        print(err)

new_name = input("삭제이름:")
deleteData(new_name)


검색하기
def selectPartData(self, name):
    try:
        c = sqlite3.connect("per.db")
        cursor = c.cursor()
        sql = "select * from person where name like ?"        arg =('%' +name+'%',)
        cursor.execute(sql, arg)
        data = cursor.fetchall()
        c.close()
        print("성공")
        return data
    except Exception as err:
        print(err)
        return None


def selectData(name, age):
    try:
        c = sqlite3.connect("per.db")
        cursor = c.cursor()
        #sql = "select * from person where name=? and age>?"        #sql = "select * from person where name=? and age in (30,40)"        #sql = "select * from person where name=? and age between 20 and 40" #  20 <= age <=40        #sql = "select * from person where name like %철%" # 이름에 철 포함된 모든 것을 가져옴.        #sql = "select * from person where name like 철%" # 이름이 철로 시작 하는 것        #sql = "select * from person where name like %철" # 이름이 철로 끝나는 것
        #sql = "select * from person order by name" # 이름으로 정렬 ㄱㄴㄷ        #sql = "select * from person order by name desc" # 이름으로 내림 차순 정렬 ㅎㅍㅌ        #sql = "select * from person limit 3" #3개만 가져옴.        #sql = "select * from person order by age desc limit 3" # 가장 나이 많은 3개만 가져옴.
        #sql = "select count(age) from person " # 나이 항목의 개수 (나이가 빈 경우가 없으면 row와 같음)        #sql = "select count(*) from person " # row의 개수. 결과는 cursor.fetchone() 하면 tuple로 결과가 나옴.        #sql = "select max(age) from person " # 가장 많은 나이        #sql = "select avg(age) from person "        #sql = "select sum(age) from person "        sql = "select max(age) sum(age) from person " # 결과가 2개이기 때문에 cursor.fetchall() 하면 2항 튜플이 온다.
        #data = (name, age)        #cursor.execute(sql, data) # 결과 값이 메모리에 loading 됨.        cursor.execute(sql)

        # data = cursor.fetchall() # 메모리에 올라가 있는 값을 한꺼번에 가져오게 됨. [(),] 형태임.        # for n, a in data:        #     print(n, a)
        for n, a in cursor: # 메모리에 올라가 있는 값을 하나씩 가져오기.            print(n,a)

        c.close()
        print("성공")
    except Exception as err:
        print(err)




def showData(sortup = False):
    print("="*60, "이름       국어     영어      수학       총점      평균", "="*60, sep='\n')
    try:
       c = sqlite3.connect("grade.db")
       if (sortup == False):
         sql = "select * from grade"       else:
         sql = "select * from grade order by name"       cursor = c.cursor()
       cursor.execute(sql)
       for i in cursor:
           s = sum(i[1:])
           print("{:5} {:10} {:10} {:10} {:10} {:10.2f}".format(i[0], i[1], i[2], i[3], s, s/3))

       sql = "select avg( kor ), avg( eng ), avg( math ) from grade "       cursor = c.cursor()
       cursor.execute(sql)
       a = cursor.fetchone()
       print("과목별 평균 {:10.2f} {:10.2f} {:10.2f}".format(float(a[0]), float(a[1]), float(a[2])))

       c.close()
    except Exception as err:
        print(err)



Python Search

검색할 때는 for loop으로 비교를 해도 되지만,
filter를 쓰면 편함. filter는 generator를 생성 함.

a = filter(조건, 대상) 

2018년 6월 26일 화요일

Python Excel

xlsxWriter : 쓰기 전용
openpyXl : 읽기 쓰기 모두 가능


import openpyxl

wb = openpyxl.Workbook()
ws1 = wb.active
ws1.title = "sheet1"
ws2 = wb.create_sheet('sheet2')

ws1['A1'] = 10ws1['A2'] = 20ws1['A3'] = '=sum(A1:A2)'
ws1.append([10,200,30])
ws1.append([40,50,60])

ws2['A1'] = 'korea'wb.save('my..xlsx')




import openpyxl

wb = openpyxl.load_workbook('my..xlsx')
ws1 = wb['sheet1']
a1 = ws1['A1'].value
print(a1)


print(wb['sheet1']['A1'].value)
wb['sheet1']['A1'].value = 'hello'wb['sheet1']['A2'].value = 'hi'
wb.save('my.xlsx')




import openpyxl

wb = openpyxl.load_workbook("my1.xlsx")
ws = wb['Sheet']
print(ws.max_row, ws.max_column)
print(ws.rows)

for c1, c2, c3, c4 in ws.rows:
    print (c1.value, c2.value, c3.value, c4.value)



import openpyxl

wb = openpyxl.Workbook()
ws = wb.active

count = 0while True:
    name = input("이름:")
    age  = int(input("나이:"))
    ws.append([name, age])
    yn = input("계속입력(y/n)? ")
    if yn == 'n':
        breakwb.save("my2.xlsx")

wb2 = openpyxl.load_workbook("my2.xlsx")
ws2 = wb2['Sheet']

for c1, c2 in ws2.rows:
    print(c1.value, c2.value)





import openpyxl
from openpyxl.chart import BarChart, LineChart, Reference

wb = openpyxl.Workbook()
ws = wb.active

ws.append(["이름", "국어", "영어"])
ws.append(['순신', 50, 30])
ws.append(['길동', 80, 50])
ws.append(['꺽정', 30, 70])
ws.append(['영수', 10, 20])

chart = BarChart()
chart.style = 10 # 색상chart.title = "점수"chart.x_axis.title = "이름"chart.y_axis.title = "점수"
data = Reference(ws, min_col=2, max_col=3, min_row=1, max_row=5) #데이터 영역cat = Reference(ws, min_col=1, min_row=2, max_row=5) # x 축의 이름 : category
chart.add_data(data, titles_from_data=True)
chart.set_categories(cat)
ws.add_chart(chart, "F1")
wb.save("char.xlsx")

Python BeautifulSoup


퍼블릭 xml 리소스들

https://www.data.go.kr/
http://www.weather.go.kr/weather/lifenindustry/sevice_rss.jsp


# xml -> beautifulsoup을 쓴다.# 설치 필요#
from bs4 import BeautifulSoup

fp = open("song.xml")
soup = BeautifulSoup(fp, "html.parser")
#print(type(soup), soup)
# soup은 xml의 root element를 나타냄.# . 으로 후손 접근 가능함. 직접 자식이 아니어도 됨. .find("후손명")도 동일 함.
print(soup.songlist.song) # OKprint(soup.song) # OKsng = soup.song
print(sng.title)
print(sng.title.text)

sngs = soup.findAll('song') # bs4.element.ResultSet 타입의 object를 갖는 리스트 임.print(type(sngs))
print(sngs[1].title.string)

for s in sngs:
    print(s['album'])

print(sngs[1].parent)

# sibling : findPrevious, findNext. Sibling은 부모가 달라고 레벨이 같은 친구들임.
print(sngs[1].findPrevious('song'))
print(sngs[1].findNext('song'))

soup.find('song', {'album':'BB'}) # 속성 검색

class A:
    def __init__(self):
        a = 0
a = A()
print(a)
# 어떻게 soup은 object인데 print하면 텍스트가 나오나 ?
# __repr__ 메소드를 구현해 주면 된다.



RSS 리더

from bs4 import BeautifulSoup
import urllib.request as REQ

jurl = "http://rss.joins.com/joins_news_list.xml"response = REQ.urlopen(jurl)

soup = BeautifulSoup(response, "html.parser")
#print(soup)
items = soup.findAll("item")

for i in items:
    print("기사제목:", i.title.string )
    print("기사내용:", i.description.string)
    print("-"*20)


HTML에서 일부 가져오기

from bs4 import BeautifulSoup
import urllib.request as REQ

nurl = "http://news.naver.com"response = REQ.urlopen(nurl)

soup = BeautifulSoup(response, "html.parser")
#print(soup)
items = soup.findAll("div", {'class':'newsnow_tx_inner'})
for i in items:
    print(i.strong.string)


추가하기
from bs4 import BeautifulSoup

fp = open("song.xml")
soup = BeautifulSoup(fp, "html.parser")

print(soup)

# 항목 추가 방법n_song   = soup.new_tag('song', album='Cheap Thrills')
n_title  = soup.new_tag('title')
n_title.string = 'Chandlier'n_singer = soup.new_tag('singer')
n_singer.string = 'Sia'
n_song.append(n_title)
n_song.append(n_singer)

soup.songlist.append(n_song)
print (soup)

# 변경된 내용을 저장하기 위해서는 문자여로 변환 필요.s = soup.prettify() # s는 object가 아니라 stringprint(s)

f = open("song.xml", "w")
f.write(s)
f.close()




삭제하기
from bs4 import BeautifulSoup

fp = open("song.xml")
soup = BeautifulSoup(fp, "html.parser")
print(soup)
soup.song.decompose()
print(soup)

기상청 날씨
from bs4 import BeautifulSoup
import urllib.request as REQ

nurl = "http://www.weather.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=109"response = REQ.urlopen(nurl)

soup = BeautifulSoup(response, "html.parser")
locations = soup.findAll("location")

def printCity(location):
    print(location.city.string)
    print("-"*10)
    datas = location.findAll('data')
    for d in datas:
        print(d.tmef.string, d.wf.string, d.tmn.string, d.tmx.string, sep="\n")

def printWeather():
    for location in locations:
        printCity(location)

def searchWeather():
    city = input("검색지역을 입력하세요 : ")
    cities = soup.findAll('city')
    for c in cities:
        if (c.string == city):
            printCity(c.parent)
            break
def showTop5():
    tmx = soup.findAll("tmx")
    sml = sorted(tmx, key=lambda n:n.string, reverse=True)[:5]
    for t in sml:
        print(t.parent.parent.city.string, t.parent.tmef.string, t.parent.wf.string, t.string)

while True:
    print("서울 경기 주간 예보")
    m = int(input("1. 서울 경기 지역 날씨 정보\n2. 지역 검색\n3. 최고기온 top5\n>"))
    {1:printWeather, 2:searchWeather, 3:showTop5}.get(m)()

Python Libs

# 객체 저장import pickle

def obWrite():
    myList = [10,20,30,40]
    fp = open("ob.txt", "wb")
    pickle.dump(myList, fp)
    fp.close()

def obRead():
    fp = open("ob.txt", "rb")
    my = pickle.load(fp)
    fp.close()
    print(my)

obWrite()
obRead()





# sqlite db에  키, 값 저장 (딕셔너리와 유사)import shelve

def shelveWrite():
    sh = shelve.open('my') # my.dat DB에 저장 되는 것임.    sh['name'] = '홍길동'    sh['age'] = 20    sh['data'] = [10, 20, 30,40]
    sh.close()

def shelveRead():
    sh = shelve.open('my')
    sh.pop('name') # 삭제    for s in sh:
        print(s, sh[s])

shelveWrite()
shelveRead()


Python File

def writeFile():
    with open("test.txt", "w") as fp: # w, r, a, t, b        fp.write("abc\ndef\nghi")

def writeFile2():
    with open("test.txt", "w") as fp: # w, r, a, t, b        fp.write("kor\nea") # text 모드에서는 \n은 \r\n으로 기록된다. binary 모드에서는 변경하지 않고 그대로 쓴다.
def readFile():
    with open("test.txt") as  fp:
        while True:
          rd = fp.read(3)
          if not rd:
              break          print(rd)
          print(fp.tell())

def readFile2():
    with open("test.txt") as fp:
      for l in fp: # readline으로 동작 함. # text 모드에서는 \r\n을 \n로 바꿔 읽어 준다. binary 모드에서는 변경 않고 그대로 읽는다.          print(l)


def readFile3():
    with open("test.txt") as fp:
      ll = fp.readlines()
      ll = [n.strip() for n in ll ]
      print(ll)

writeFile2()
readFile3()