如何使用Tensorflow和Python將Unicode字串表示為UTF-8編碼的字串?
可以使用“encode”方法將一組Unicode字串表示為UTF8編碼的字串。
閱讀更多:什麼是TensorFlow以及Keras如何與TensorFlow一起建立神經網路?
處理自然語言的模型處理具有不同字元集的不同語言。Unicode被認為是標準的編碼系統,用於表示幾乎所有語言的字元。每個字元都使用一個唯一的整數程式碼點進行編碼,該程式碼點介於0和0x10FFFF之間。Unicode字串是零個或多個程式碼值的序列。
讓我們瞭解如何使用Python表示Unicode字串,以及如何使用Unicode等效項來操作這些字串。首先,我們使用標準字串操作的Unicode等效項,根據指令碼檢測將Unicode字串分成標記。
我們正在使用Google Colaboratory執行以下程式碼。Google Colab或Colaboratory幫助在瀏覽器上執行Python程式碼,並且無需任何配置,並且可以免費訪問GPU(圖形處理單元)。Colaboratory構建在Jupyter Notebook之上。
print("A set of Unicode strings which is represented as a UTF8-encoded string")
batch_utf8 = [s.encode('UTF-8') for s in[u'hÃllo', u'What is the weather tomorrow',u'Göödnight', u'😊']]
batch_chars_ragged = tf.strings.unicode_decode(batch_utf8,
input_encoding='UTF-8')
for sentence_chars in batch_chars_ragged.to_list():
print(sentence_chars)
print("Dense tensor with padding are printed")
batch_chars_padded = batch_chars_ragged.to_tensor(default_value=-1)
print(batch_chars_padded.numpy())
print("Converting to sparse matrix")
batch_chars_sparse = batch_chars_ragged.to_sparse()程式碼來源:https://www.tensorflow.org/tutorials/load_data/unicode
輸出
A set of Unicode strings which is represented as a UTF8-encoded string [104, 195, 108, 108, 111] [87, 104, 97, 116, 32, 105, 115, 32, 116, 104, 101, 32, 119, 101, 97, 116, 104, 101, 114, 32, 116, 111, 109, 111, 114, 114, 111, 119] [71, 246, 246, 100, 110, 105, 103, 104, 116] [128522] Dense tensor with padding are printed [[ 104 195 108 108 111 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1] [87 104 97 116 32 105 115 32 116 104 101 32 119 101 97 116 104 101 114 32 116 111 109 111 114 114 111 119] [71 246 246 100 110 105 103 104 116 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1] [128522 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1]] Converting to sparse matrix
解釋
- 當解碼多個字串時,每個字串中的字元數可能不相等。
- 結果將是一個tf.RaggedTensor,其中最內層維度的長度會發生變化,並且這種變化取決於每個字串中的字元數。
- 可以直接使用此tf.RaggedTensor,或者可以使用tf.RaggedTensor.to_tensor方法將其轉換為具有填充的密集tf.Tensor,或者使用tf.RaggedTensor.to_sparse方法將其轉換為tf.SparseTensor。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP