이번 포스팅에서는 Python의 Dictionary로 Key: Value 매핑하여 문자열을 변경해주는 replace() 함수를 사용하여 SQL query 코드의 여러개의 문자열을 변경하는 방법을 소개하겠습니다. 

코드가 길고 동일한 특정 변수나 테이블 이름이 여러번 나오는 경우, 수작업으로 일일이 하나씩 찾아가면서 변수나 테이블 이름을 변경하다보면 사람의 실수(human error)가 발생할 위험이 큽니다.  이럴 때 Dictionary에 (변경 전 : 변경 후) 매핑을 관리하고 컴퓨터에게 코드 변경을 시킬 수 있다면 사람의 실수를 예방하는데 도움이 될 것입니다. 

 

먼저, 예제로 사용할 SQL query와 Key(Before, 변경 전): Value(After, 변경 후) 를 매핑한 Dictionary 를 만들어보겠습니다. 

 

## key(Before): value(After) mapping dictionary
map_dict = {
    'X1': '"변수1"', # Key(Before): Value(After)
    'X2': '"변수2"', 
    'X3': '"변수3"',
    'MYTABLE': 'TEST_TABLE'
}


sql_query = "select \nx1, x2, x3 \nfrom mytable \nwhere x2 > 10 \nlimit 10;"

print(sql_query)
# select 
# x1, x2, x3 
# from mytable 
# where x2 > 10 
# limit 10;

 

 

 

아래에는 여러개의 줄(lines)을 가지는 문자열을 하나의 줄(line)로 나누어주는 splitlines() 메소드와, Dictionary의 Key, Value를 쌍으로 반환해주는 items() 메소드를 소개하였습니다. 

 

## splitlines()
for l in sql_query.splitlines():
    print(l)

# select 
# x1, x2, x3 
# from mytable 
# where x2 > 10 
# limit 10;



## replace(a, b) method convert a string 'a' with 'b'
s = 'Hello Python World.'
s.replace('Hello', 'Hi')

# 'Hi Python World.'



# dictionary.items() ==> returns key, value
for k, v in map_dict.items():
    print(k, ':', v)

# X1 : "변수1"
# X2 : "변수2"
# X3 : "변수3"
# MYTABLE : TEST_TABLE

 

 

 

위에서 기본적인 splitlines(), replace(), items() 메소드에 대한 사용법을 알았으니, 이제 이를 엮어서 코드에 있는 여러개의 특정 변수나 테이블 이름을 Dictionary(변경 전 이름 Key: 변경 후 이름 Value 매핑) 에서 가져와서 replace() 메소드로 변경해주는 사용자 정의함수를 만들어보겠습니다. 

 

## User Defined Function for converting codes 
## using replace() function and dictionary(Before: After mapping)
def code_converter(codes_old, map_dict):
    # blank string to save the converted codes
    codes_converted = ''
    
    # converting codes using replace() function and dictionary(Before: After mapping)
    for code in codes_old.splitlines():
        for before, after in map_dict.items():
            code = code.upper().replace(before, after)
            
        codes_converted = codes_converted + code + '\n'
        
    return codes_converted
    

## executing the UDF above
sql_query_new = code_converter(sql_query, map_dict)


print(sql_query_new)
# SELECT 
# "변수1", "변수2", "변수3" 
# FROM TEST_TABLE 
# WHERE "변수2" > 10 
# LIMIT 10;

 

 

이번 포스팅이 많은 도움이 되었기를 바랍니다. 

행복한 데이터 과학자 되세요!  :-)

 

728x90
반응형
Posted by Rfriend
,