Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách tách chuỗi Unicode và chỉ định byte offset với TensorFlow & Python

Chuỗi Unicode có thể được tách và byte offset được chỉ định bằng hai phương thức:

  • unicode_split – tách chuỗi Unicode thành các ký tự con.
  • unicode_decode_with_offsets – giải mã kèm byte offset của mỗi ký tự.

Cả hai đều nằm trong module tf.strings.

Mã ví dụ

print("Tách chuỗi Unicode")
tf.strings.unicode_split(thanks, 'UTF-8').numpy()

codepoints, offsets = tf.strings.unicode_decode_with_offsets(u"🎈🎉🎊", 'UTF-8')
print("In byte offset cho các ký tự")
for (codepoint, offset) in zip(codepoints.numpy(), offsets.numpy()):
    print("At byte offset {}: codepoint {}".format(offset, codepoint))

Nguồn mã: TensorFlow Unicode Tutorial

Đầu ra

Tách chuỗi Unicode
In byte offset cho các ký tự
At byte offset 0: codepoint 127880
At byte offset 4: codepoint 127881
At byte offset 8: codepoint 127882

Giải thích

  • tf.strings.unicode_split tách chuỗi Unicode thành các chuỗi con ký tự đơn lẻ.
  • Tensor ký tự tạo ra cần căn chỉnh với chuỗi gốc bằng unicode_decode.
  • Cần biết offset bắt đầu của mỗi ký tự để căn chỉnh.
  • unicode_decode_with_offsets tương tự unicode_decode nhưng trả thêm tensor thứ hai chứa offset bắt đầu của mỗi ký tự.