수 많은 우문은 현답을 만든다

Python 본문

개발지식/Programming Language

Python

aiden.jo 2020. 7. 10. 17:21

안녕하세요, 조영호입니다.

Hi, Today I am going to share the basic grammar of Python programming language.

Python is commonly used for NLP(Natural Language Processing) and Big-data processing. Actually, I use JAVA programming language usually but I studied Python at this time to be ready for extending my skill. I prepared important points of python grammar.

 

Remark for Korean (한글 주석)

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

 

Output Statement(출력문)  

일반 출력 예제 (n이 1일때)
print(“test %s” % n) => test 1
print(“test %s %s” % (n, n+1))  => test 1 2
print(“test %s”, n) => test, 1
print 100, ‘ * ‘, n => 100 * 1
print n[::3] -> Print first one and then print others with interval 3
print(“test %s” + n) => ERROR(cannot concatenate ‘str’ and ‘int’ objects)

특수 출력 예제

lambda (make function as one line)
  (lambda x, y : x + y)(10,20) => 30

map (extract factor from array and then return a array result that calculated by a function)
 ()

reduce (return an accumulated list)
  reduce(lambda x, y : x + y, [0, 1, 2, 3]) -> 6

filter (return a filterd list)
  filter(lambda x : x < 5, range(0, 10))

 

자료형

수치형(numbers) : int, long int, float
순서형(sequence) : list, string, 튜플(tuple), User defined class
매핑(mapping) : Dictionary, Class Instance, C extension

 

문자열 (List)

append (add character, 문자 추가)
  str.append(‘a’)

[:] (range of array, 문자열 범위)
  str[2:4] -> from 2 to 3
  str[:3] -> from 0 to 3

sort
  list.sort() -> change origin list(원본 문자열 자체를 바꿔버림)
  sorted(list) -> return new ordered list(정렬된 새로운 리스트 반환)

del (delete character, 문자 자우기)
  del str[0]

 

튜플(tuple — 묶음)

Tuple
(a, b, *rest) => 1, 2, 3, 4, 5가 인자일때 1, 2, (3, 4, 5) 로 묶임

Shifting
(without temp)
  a, b = b, a => 일반적으로 사용하는 temp 변수가 필요없다.

Making Tuple
  t = (‘a’, ‘b’, ‘c’)
  t = ‘a’, ‘b’, ‘c’ //same way
  empty = () //must need () when tuple is empty(빈 튜플은 소괄호 필수)
  one = (1,). //must need , when tuple has only a factor(단일 튜플은 콤마 필수)

Tuple vs List (튜플 <-> 리스트)
  tuple(l) //change list to tuple
  list(t)    //change tuple to list

Cutting Tuble(튜플 자르기)
 We cannot change the origin factor, so need to cut the tuple
 ex) p = (1,2,3)
 q = p[:1] + (5,) + p[2:] => 1,5,3

 

넘피(Numpy is based the Pands and array library)

A list has the same types of fators(같은 타입의 원소들만 있는 리스트)
Import numpy
  dot(a,b) //행렬 간의 곱셈

 

셋(set)

has an Unique key(유일한 키값을 가진다)

list를 타입캐스팅 해서 (set(list)) set으로 만들 수 있으며 중복 데이터는 알아서 하나의 값으로 된다.

메소드 : add, remove, keyName in setName, &(and연산), union(or연산), issubset()

 

사전(hash)

선언 : dic = {‘key’ : ‘value’, ‘key2’ : ‘value2’}
추가 : dic[‘key3’] = ‘value3’
리스트로 바꾸기 : dic.keys(), dic.values()
검색 : ‘key’ in dic


Module(모듈)

전체 인용 : Import math, calendar (권장 : 그러나 math.pi 처럼 매번 모듈명을 먼저 호출해줘야함)
부분 인용 : from Tkinter import *. (비권장 : Tkinter에 Lable이라는 변수가 있는데 사용자가 Lable이라고 다른 의도의 변수를 지정하면 충돌발생)
모듈 관리 : del 모듈, reload(모듈)
모듈 종류
— import sys : 파이썬 인터프리터 조작 (sys.ps1, sys.exit())
— import os : OS 조작
    os.getcwd()
    os.listdir(‘path’)
    os.rename(‘a’, ‘b’))
    os.path.isdir(x) //디렉토리인가

— import webbrowser
    webbrowser.open(‘url’)

— import random
    random.random() //0<=x<1
    random.randrange(1,7) //1<=x<7
    random.shuffle(list)
    random.choice(list)

— import re : 정규식

— import glob : 파일 리스트 뽑기
    p = re.compile(‘.*p.*n.*’) //p뒤에 n이 오는 조건
    for I in glob.glob(‘*’) // 모든 파일 리스트
    m = p.match(I) //매칭조회
    if m: print m.group() //정규식의 실제 결과 문자열은 group()으로 얻는다. 그냥 print하면 0x1065d2578 이라고 이름이 나옴.

— import string : 문자열 연산
    string.capitalize(‘ab’) => Ab
    string.replace(‘ab’, ‘a’->’c’) => cb
    string.split(‘a b c’) => [‘a’, ‘b’, ‘c’] //list type

 

Pandas(판다 — 데이터 분석 라이브러리)

Import pandas as pd

dataframe = pd.read_csv(filename) //데이터프레임이 csv 형태를 테이블로 출력까지 해줌
dataframe.head(n) //n은 몇줄 보일거냐고 빈칸이면 default 5라인
Newdf = dataframe[ [‘컬럼명’] ] // 특정 컬럼만 추출해서 새로운 데이터 프레임에 담을 수 있다.

df.ix[행,열] // 특정 행,렬 위치의 칼럼의 값을 반환
df.ix[행,’열 이름’] //이런 식으로도 가능
df.ix[0:2, ‘행이름’:’열이름’] //테이블 자체를 추출해 해버린다 가로범위~세로범위
df[‘컬럼명’].unique() // 중복 제거 된 값들만 뽑아냄

Newer = df[df[‘컬럼명’]>=10] //조건을 걸어 테이블 뽑아냄
Newer.to_csv(‘csvName’)

 

File handling(파일)

열기
f = open(‘dir’)
f = open(‘dir’, w) //쓰기 모드, write 옵션은 기존의 내용도 백지로 만들고 시작함
f = open(‘dir’, a) //이어쓰기 모드, append 옵션은 기존의 내용에 추가함
읽기
f.read() //개행문자를 \n으로 표시하며 한 줄로 읽음
f.readline() //한줄씩읽기
print f //개행문자가 앤터로 인식이 되어 출력됨
쓰기
f.write(‘text’)

Class(클래스)

1. Self
객체 자신을 가리킴
2. 초기화 메소드 (생성자)
def __init__(self): //객체 생성시 자동으로 실행됨

 

감사합니다.