บทนำ
TensorFlow มี operations สำหรับวัดความยาวและแปลง encoding ของ Unicode strings:
tf.strings.length: วัดความยาว (รองรับ unit: BYTE, UTF8_CHAR, UTF16_CHAR)tf.strings.unicode_encode: code points → encoded stringtf.strings.unicode_decode: encoded string → code pointstf.strings.unicode_transcode: แปลง encoding (เช่น UTF-8 → UTF-16-BE)
โค้ดตัวอย่าง
print("The final character takes about 4 bytes in UTF-8 encoding")
thanks = u'Hello 😊'.encode('UTF-8')
num_bytes = tf.strings.length(thanks).numpy()
num_chars = tf.strings.length(thanks, unit='UTF8_CHAR').numpy()
print('{} bytes; {} UTF-8 characters'.format(num_bytes, num_chars))ผลลัพธ์
The final character takes about 4 bytes in UTF-8 encoding 10 bytes; 7 UTF-8 characters
คำอธิบาย
- "Hello 😊" = 6 ASCII chars (6 bytes) + 😊 (4 bytes) = 10 bytes
- แต่เป็น 7 Unicode characters (H,e,l,l,o, space, 😊)
unit='UTF8_CHAR'ให้นับ code points แทน bytes- สิ่งนี้สำคัญสำหรับ: padding, truncation, positional encoding ใน NLP models
สรุป Operations หลัก
| Operation | หน้าที่ |
|---|---|
| length | วัดความยาว (byte หรือ char) |
| unicode_decode | string → code points (int32 vector) |
| unicode_encode | code points → string (encoding 指定) |
| unicode_transcode | string (encoding A) → string (encoding B) |
| unicode_split | string → substrings ตัวอักษรเดี่ยว |
| substr | ตัด substring (รองรับ char unit) |