บทนำ
TensorFlow มี 3 operations หลักสำหรับแปลงระหว่างรูปแบบ string representations:
unicode_decode: encoded string scalar → vector of code pointsunicode_encode: vector of code points → encoded string scalarunicode_transcode: encoded string scalar (encoding A) → encoded string scalar (encoding B)
โค้ดตัวอย่าง
print("Converting encoded string scalar to a vector of code points")
tf.strings.unicode_decode(text_utf8, input_encoding='UTF-8')
print("Converting vector of code points to an encoded string scalar")
tf.strings.unicode_encode(text_chars, output_encoding='UTF-8')
print("Converting encoded string scalar to a different encoding")
tf.strings.unicode_transcode(text_utf8, input_encoding='UTF8', output_encoding='UTF-16-BE')ผลลัพธ์
Converting encoded string scalar to a vector of code points Converting vector of code points to an encoded string scalar Converting encoded string scalar to a different encoding
คำอธิบาย
unicode_decode: แปลง byte string (UTF-8, UTF-16, etc.) → int32 tensor ของ code pointsunicode_encode: แปลง int32 tensor (code points) → byte string ด้วย encoding ที่ระบุunicode_transcode: แปลง encoding โดยตรง ไม่ต้อง decode→encode เอง (มีประสิทธิภาพกว่า)- รองรับ encoding ทุกชนิดที่ ICU รองรับ (UTF-8, UTF-16-BE/LE, UTF-32, Latin-1, ฯลฯ)
กรณีใช้งาน
- Preprocessing: decode UTF-8 → code points → model input
- Postprocessing: model output (code points) → encode → UTF-8 string
- Interop: รับข้อมือ UTF-16 จากระบบอื่น → transcode → UTF-8 สำหรับ TensorFlow