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

Cách chuyển đổi giữa các biểu diễn chuỗi khác nhau với TensorFlow

TensorFlow cung cấp ba phép chuyển đổi chính cho chuỗi Unicode:

  • unicode_decode: chuỗi mã hóa vô hướng (encoded string scalar) → vector mã điểm (code points).
  • unicode_encode: vector mã điểm → chuỗi mã hóa vô hướng.
  • unicode_transcode: chuỗi mã hóa này → chuỗi mã hóa khác (ví dụ UTF-8 → UTF-16-BE).

Mã ví dụ

print("Chuyển chuỗi mã hóa -> vector mã điểm")
tf.strings.unicode_decode(text_utf8, input_encoding='UTF-8')

print("Chuyển vector mã điểm -> chuỗi mã hóa")
tf.strings.unicode_encode(text_chars, output_encoding='UTF-8')

print("Chuyển đổi encoding (UTF-8 -> UTF-16-BE)")
tf.strings.unicode_transcode(text_utf8, input_encoding='UTF8', output_encoding='UTF-16-BE')

Nguồn mã: TensorFlow Unicode Tutorial

Đầu ra

Chuyển chuỗi mã hóa -> vector mã điểm
Chuyển vector mã điểm -> chuỗi mã hóa
Chuyển đổi encoding (UTF-8 -> UTF-16-BE)
<tf.Tensor: shape=(), dtype=string, numpy=b'\x8b\xed\x8a\x00Y\x04t\x06'>

Giải thích

  • unicode_decode: encoded scalar → vector code points.
  • unicode_encode: vector code points → encoded scalar.
  • unicode_transcode: chuyển đổi giữa các encoding (UTF-8, UTF-16-BE, v.v.).