บทนำ
tf.strings.substr ใช้ตัด substring แบบระบุตำแหน่งและความยาว รองรับหน่วยเป็น BYTE (default) หรือ UTF8_CHAR
โค้ดตัวอย่าง
print("The default unit is byte")
print("When len is 1, a single byte is returned")
tf.strings.substr(thanks, pos=7, len=1).numpy()
print("The unit is specified as UTF8_CHAR")
print("It takes up 4 bytes")
print(tf.strings.substr(thanks, pos=7, len=1, unit='UTF8_CHAR').numpy())ผลลัพธ์
The default unit is byte When len is 1, a single byte is returned The unit is specified as UTF8_CHAR It takes up 4 bytes b''
คำอธิบาย
- Default
unit='BYTE':posและlenนับเป็น byte → ตัด emoji ได้แค่ 1 byte (เสียหาย) unit='UTF8_CHAR': นับเป็น Unicode character → ตัด emoji ได้ 1 ตัวสมบูรณ์ (4 bytes)- พารามิเตอร์
unitกำหนดการตีความ pos/len (รองรับ BYTE, UTF8_CHAR, UTF16_CHAR)
ข้อควรระวัง
การใช้ BYTE unit กับ multi-byte characters (emoji, ภาษาเอเชีย) จะทำให้ substring ตัดกลางตัวอักษร → invalid UTF-8 ควรใช้ UTF8_CHAR สำหรับ text processing ที่ต้องการความถูกต้องระดับตัวอักษร