본문 바로가기

수업정리/Fundamental

Python basic 4 - map(), import, zip() 한글을 입력하면 유니코드로

         my_utils.py                 >                   map_hex_name.py

한글을 입력하면 유니코드로            문자열을 입력하면 유니코드로

hex(ord(char)), int(hex(ord(char)), 16)  <-- 나중에 zip 으로 결과를 묶는데 int_hex 는 chr() 로 변형해 한글자로 변형하고

hex 는 그냥 유니코드이다.

 

map() 내가 정의한 변수로 각각의 객체를 맵핑시켜준다.

def myfunc(n):
  return len(n)

x = map(myfunc, ('apple', 'banana', 'cherry'))

print(list(x)) # [5, 6, 6]

내가 apple, banana, cherry 를 내가 정의한 문자열의 길이를 값으로 가지는 함수로 mapping 시켜주면 x 는 map 함수의 반환 값은 map객체 가 나온다.

해당 자료형을 list 혹은 tuple로 형 변환시켜주어야 한다.

list(x) 로 변형시켜 주면 5, 6, 6 이 담긴리스트가 된다.

 

이제 우리는 map() 을 이용해 한글을 입력하면 유니코드를 알려주는 코드를 만들어볼 것이다.

my_utils.py

#coding: utf-8
 def _hex(char):
     return hex(ord(char))
 def _hex_int(char):
     return int(hex(ord(char)), 16)
 if __name__ == '__main__':
     '''So far, we did two-three steps
     to print unicode string using hexa code_points,
     ord(''), hex(ord(''), int(hex(ord('')), 16), chr(integer value)
     'map() function returns a map object of the results
     after applying the given function to each item of a given iterable(list, tuple)'''
     #map(myfunction, iterable)

     my_hex = map(_hex, ('한', '글'))
     print(my_hex) # shows the object address
     print(tuple(my_hex)) # shows the content of the object

     my_hex = map(_hex, ['한', '글'])
     print(my_hex)
     print(list(my_hex))

     my_hex_int = map(_hex_int, list('한글'))
     print(my_hex_int)
     print(list(my_hex_int))

 

'한', '글' 을 각자 hex(ord(char)) 로 문자를 int 로 변형한 것을 16진법으로 바꾸어 맵핑 한다.
그 결과들을 각각 tuple, list 로 만든다.

마지막은  int(hex(ord(char)), 16) 문자를 int 로 변형한 것을 int 로 저장하는 것이다. ( 그냥 ord(char) 하는거랑 똑같음 )

 

이제 이 파일을 import 해서 내 이름의 유니코드를 반환하는 것을 만들어보자

map_hex_name.py

 #coding: utf-8
 from my_utils import _hex, _hex_int

 my_hex = map(_hex, list('홍길동'))
 my_hex_int = map(_hex_int, list('홍길동'))
 for each in zip(my_hex, my_hex_int):
     print(each[0], chr(each[1]), type(each[0]), type(each[1]))