บทนำ
TensorFlow มี ops สำหรับจัดการ Unicode string ระดับตัวอักษร:
tf.strings.unicode_split: แยก string เป็น substring ตัวอักษรเดี่ยวtf.strings.unicode_decode_with_offsets: decode พร้อมคืนค่า byte offset เริ่มต้นของแต่ละตัวอักษร
โค้ดตัวอย่าง
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))ผลลัพธ์
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
คำอธิบาย
- Emoji 🎈🎉🎊 แต่ละตัวเข้ารหัส UTF-8 ใช้ 4 bytes (offset 0, 4, 8)
unicode_splitคืนค่า tensor ของ substring (แต่ละตัวอักษร)unicode_decode_with_offsetsคืนค่า (codepoints, offsets) โดย offsets บอกตำแหน่ง byte ใน string ดั้งเดิม- จำเป็นตอน align character tensor กับ original string (เช่น สำหรับ character-level models หรือ highlight)
กรณีใช้งาน
Byte offsets สำคัญเมื่อต้อง map ระหว่าง character-level representation กลับไปยัง raw string (เช่น NER, POS tagging, highlight search results)