How can Tensorflow text be used to split the UTF-8 strings in Python?

The UTF-8 strings can be split using Tensorflow text. This can be done with the help of ‘UnicodeScriptTokenizer’. ‘UnicodeScriptTokenizer’ is a tokenizer that is created, after which the ‘tokenize’ method present in ‘UnicodeScriptTokenizer’ is called on the string.

Read More: What is TensorFlow and how Keras work with TensorFlow to create Neural Networks?

We will use the Keras Sequential API, which is helpful in building a sequential model that is used to work with a plain stack of layers, where every layer has exactly one input tensor and one output tensor.

A neural network that contains at least one layer is known as a convolutional layer. We can use the Convolutional Neural Network to build learning model. 

TensorFlow Text contains collection of text related classes and ops that can be used with TensorFlow 2.0. The TensorFlow Text can be used to preprocess sequence modelling.

We are using the Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook.

Tokenization is the method of breaking down a string into tokens. These tokens can be words, numbers, or punctuation.

The important interfaces include Tokenizer and TokenizerWithOffsets each of which have a single method tokenize and tokenize_with_offsets respectively. There are multiple tokenizers, each of which implement TokenizerWithOffsets (which extends the Tokenizer class). This includes an option to get byte offsets into the original string. This helps know the bytes in the original string the token was created from.

All the tokenizers return RaggedTensors with the inner-most dimension of tokens that are mapped to the original individual strings. The resulting shape's rank increases by one.


print("Unicode script tokenizer is being called")
tokenizer = text.UnicodeScriptTokenizer()
tokens = tokenizer.tokenize(['everything not saved will be lost.', u'Sad☹'.encode('UTF-8')])
print("The tokenized data is converted to a list")

Code credit −


Unicode script tokenizer is being called
The tokenized data is converted to a list
[[b'everything', b'not', b'saved', b'will', b'be', b'lost', b'.'], [b'Sad', b'\xe2\x98\xb9']]


  • The tokenizer splits UTF-8 strings based on the Unicode script boundaries.

  • The script codes correspond to International Components for Unicode (ICU) UScriptCode values.

  • It is similar to the WhitespaceTokenizer with the difference that it will split punctuation (USCRIPT_COMMON) from language texts as well as separate language texts from each other.