유니코드 문자열은 unicode_split 메서드를 사용해 분할할 수 있으며, unicode_decode_with_offsets 메서드를 사용해 각 문자의 바이트 오프셋을 확인할 수 있습니다. 이 두 메서드는 모두 tensorflow 모듈의 strings 클래스에 포함되어 있습니다.
유니코드 문자열 처리 개요
먼저 Python으로 유니코드 문자열을 표현한 뒤, 유니코드에 대응하는 연산들을 활용해 해당 문자열을 조작합니다. 표준 문자열 연산의 유니코드 버전을 사용하면 스크립트 감지(script detection)를 기반으로 유니코드 문자열을 토큰 단위로 분리하는 것도 가능합니다.
Google Colaboratory에서 코드 실행하기
이 글의 예제 코드는 Google Colaboratory(Colab) 환경에서 실행됩니다. Google Colab은 브라우저에서 바로 Python 코드를 실행할 수 있게 해주며, 별도의 설정이 필요 없고 GPU(그래픽 처리 장치)를 무료로 사용할 수 있다는 큰 장점이 있습니다. Colaboratory는 Jupyter Notebook을 기반으로 구축된 서비스입니다.
print("Split unicode strings")
tf.strings.unicode_split(thanks, 'UTF-8').numpy()
codepoints, offsets = tf.strings.unicode_decode_with_offsets(u"🎈🎉🎊", 'UTF-8')
print("Printing byte offset for characters")
for (codepoint, offset) in zip(codepoints.numpy(), offsets.numpy()):
print("At byte offset {}: codepoint {}".format(offset, codepoint))코드 출처: https://www.tensorflow.org/tutorials/load_data/unicode
실행 결과
Split unicode strings Printing byte offset for characters At byte offset 0: codepoint 127880 At byte offset 4: codepoint 127881 At byte offset 8: codepoint 127882
코드 설명
tf.strings.unicode_split연산은 유니코드 문자열을 개별 문자 단위의 하위 문자열로 분할합니다.- 생성된 문자 텐서는
tf.strings.unicode_decode를 통해 원본 문자열과 정렬(매핑)되어야 합니다. - 이를 위해서는 각 문자가 시작되는 위치, 즉 오프셋(offset) 정보를 알아야 합니다.
tf.strings.unicode_decode_with_offsets메서드는unicode_decode메서드와 유사하지만, 각 문자의 시작 오프셋을 담고 있는 두 번째 텐서를 추가로 반환한다는 점이 다릅니다.