# Python tokenizer libraries

Python tokenizer libraries split text into the tokens a language model reads and map each token to an integer ID. A subword tokenizer trains its vocabulary from text rather than splitting only on spaces and punctuation. These libraries let apps and AI agents count tokens before a model call.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [tiktoken](#tiktoken) | 223.6M | 19.7K | Aug 2026 | MIT |
| [Tokenizers](#tokenizers) | 216.8M | 11.3K | Oct 2026 | Apache-2.0 |
| [Transformers](#transformers) | 116.7M | 169.2K | Nov 2026 | Apache-2.0 |
| [NLTK](#nltk) | 48.7M | 14.8K | Oct 2026 | Apache-2.0 |
| [SentencePiece](#sentencepiece) | 29.8M | 12.2K | Nov 2026 | Apache-2.0 |
| [spaCy](#spacy) | 25.2M | 34.1K | Oct 2026 | MIT |
| [Sentence Transformers](#sentence-transformers) | 22.8M | 19.3K | Nov 2026 | Apache-2.0 |
| [Jieba](#jieba) | 6.2M | 35.2K | Jan 2020 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[tiktoken](#tiktoken) has the most monthly downloads in this comparison, at 223.6M.

## Capabilities

| Library | Subword model IDs | Python three ten installation |
| --- | --- | --- |
| [tiktoken](#tiktoken) | Yes | Yes |
| [Tokenizers](#tokenizers) | Yes | Yes |
| [Transformers](#transformers) | Yes | No |
| [NLTK](#nltk) | No | Yes |
| [SentencePiece](#sentencepiece) | Yes | Yes |
| [spaCy](#spacy) | Via plugin | Yes |
| [Sentence Transformers](#sentence-transformers) | Yes | Yes |
| [Jieba](#jieba) | No | Undocumented |

## Libraries

### tiktoken

[GitHub](https://github.com/openai/tiktoken) · [PyPI](https://pypi.org/project/tiktoken) · [Docs](https://pypi.org/project/tiktoken/)

Encodes and decodes text using byte-pair tokenization for OpenAI models.

- Downloads / mo: 223.6M
- Stars: 19.7K
- Last release: 0.14.0
- License: MIT
- Capabilities: [From the tiktoken docs](https://pypi.org/project/tiktoken/)

**Strengths**

- **Selects encodings by model name.** Use encoding_for_model to select the model’s encoding.
- **Preserves token bytes for inspection.** Use decode_single_token_bytes to inspect an individual token.

**Watch out for**

- **Special-token text raises by default.** Choose allowed_special or disallowed_special behavior for text containing special-token strings.
- **Partial decoding can replace bytes.** Use byte decoding or strict errors when inspecting incomplete UTF-8 tokens.

```sh
python -m pip install tiktoken
```

**langchain-ai/langchain** (149.7K stars)

[langchain-ai/langchain](https://github.com/langchain-ai/langchain) 

```python
def __init__(
    self,
    encoding_name: str = "gpt2",
    model_name: str | None = None,
    allowed_special: Literal["all"] | AbstractSet[str] | None = None,
    disallowed_special: Literal["all"] | Collection[str] = "all",
    **kwargs: Any,
) -> None:
    """Create a new `TokenTextSplitter`.

    Args:
        encoding_name: The name of the tiktoken encoding to use.
        model_name: The name of the model to use.
            If provided, this will override the `encoding_name`.
        allowed_special: Special tokens that are allowed during encoding.
        disallowed_special: Special tokens that are disallowed during encoding.

    Raises:
        ImportError: If the tiktoken package is not installed.
    """
    if allowed_special is None:
        allowed_special = set[str]()
    super().__init__(**kwargs)
    try:
        tiktoken = cast("Any", _import_tiktoken())
    except ImportError as err:
        msg = (
            "Could not import tiktoken python package. "
            "This is needed in order to for TokenTextSplitter. "
            "Please install it with `pip install tiktoken`."
        )
        raise ImportError(msg) from err

    if model_name is not None:
        enc = tiktoken.encoding_for_model(model_name)
    else:
        enc = tiktoken.get_encoding(encoding_name)
    self._tokenizer = enc
    self._allowed_special = allowed_special
    self._disallowed_special = disallowed_special
```

[libs/text-splitters/langchain_text_splitters/base.py](https://github.com/langchain-ai/langchain/blob/80655a182f24002f78f6baf884a67e227c06d7fa/libs/text-splitters/langchain_text_splitters/base.py#L329-L368) · [More projects using tiktoken →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20tiktoken%20to%20encode%2C%20decode%20and%20prepare%20model%20tokens&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import tiktoken
encoding = tiktoken.get_encoding('o200k_base')
print(encoding.encode('Hello world'))

```

From [README.md](https://pypi.org/pypi/tiktoken/0.14.0/json#info.description)

### Tokenizers

[GitHub](https://github.com/huggingface/tokenizers) · [PyPI](https://pypi.org/project/tokenizers) · [Docs](https://pypi.org/project/tokenizers/)

Provides configurable tokenization pipelines and vocabulary training through Rust-backed Python bindings.

- Downloads / mo: 216.8M
- Stars: 11.3K
- Last release: 0.23.3
- License: Apache-2.0
- Capabilities: [From the Tokenizers docs](https://pypi.org/project/tokenizers/)

**Strengths**

- **Trains a custom vocabulary.** Train from files or an iterator of text.
- **Tracks tokens to original text.** Use offsets to recover the input span behind each token.

**Watch out for**

- **Decoding needs a matching decoder.** Configure the decoder to handle the vocabulary’s subword markers.

```sh
python -m pip install tokenizers
```

**resemble-ai/chatterbox** (27.9K stars)

[resemble-ai/chatterbox](https://github.com/resemble-ai/chatterbox) 

```python
def encode(self, txt: str):
    """
    clean_text > (append `lang_id`) > replace SPACE > encode text using Tokenizer
    """
    txt = txt.replace(' ', SPACE)
    code = self.tokenizer.encode(txt)
    ids = code.ids
    return ids
```

[src/chatterbox/models/tokenizers/tokenizer.py](https://github.com/resemble-ai/chatterbox/blob/ab55923c27757c90cfcc407baa57dc25a7d25217/src/chatterbox/models/tokenizers/tokenizer.py#L35-L42) · [More projects using Tokenizers →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20tokenizers%20to%20encode%2C%20decode%20and%20prepare%20model%20tokens&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from tokenizers import Tokenizer
tokenizer = Tokenizer.from_pretrained('bert-base-cased')
print(tokenizer.encode('Hello world').ids)

```

From [README.md](https://huggingface.co/docs/tokenizers/en/api/tokenizer)

### Transformers

[GitHub](https://github.com/huggingface/transformers) · [PyPI](https://pypi.org/project/transformers) · [Docs](https://pypi.org/project/transformers/)

Loads model-specific tokenizers and prepares encoded model inputs with padding and special tokens.

- Downloads / mo: 116.7M
- Stars: 169.2K
- Last release: 5.23.0
- License: Apache-2.0
- Capabilities: [From the Transformers docs](https://pypi.org/project/transformers/)

**Strengths**

- **Loads the matching tokenizer class.** AutoTokenizer resolves a tokenizer using the model configuration.
- **Prepares padded model input batches.** Create input IDs and attention masks with padding and truncation.

**Watch out for**

- **New tokens need matching embeddings.** Resize the model’s token embeddings after extending its vocabulary.
- **Offsets depend on the backend.** Use a fast tokenizer when requesting character offset mappings.

```sh
python -m pip install transformers
```

**langchain-ai/langchain** (149.7K stars)

[langchain-ai/langchain](https://github.com/langchain-ai/langchain) 

```python
@classmethod
def from_huggingface_tokenizer(
    cls, tokenizer: PreTrainedTokenizerBase, **kwargs: Any
) -> TextSplitter:
    """Text splitter that uses Hugging Face tokenizer to count length.

    Args:
        tokenizer: The Hugging Face tokenizer to use.

    Returns:
        An instance of `TextSplitter` using the Hugging Face tokenizer for length
            calculation.
    """
    pretrained_tokenizer_base = _import_pretrained_tokenizer_base()

    if not isinstance(tokenizer, pretrained_tokenizer_base):
        msg = "Tokenizer received was not an instance of PreTrainedTokenizerBase"
        raise ValueError(msg)  # noqa: TRY004

    def _huggingface_tokenizer_length(text: str) -> int:
        return len(tokenizer.tokenize(text))

    return cls(length_function=_huggingface_tokenizer_length, **kwargs)
```

[libs/text-splitters/langchain_text_splitters/base.py](https://github.com/langchain-ai/langchain/blob/80655a182f24002f78f6baf884a67e227c06d7fa/libs/text-splitters/langchain_text_splitters/base.py#L212-L234) · [More projects using Transformers →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20transformers%20to%20encode%2C%20decode%20and%20prepare%20model%20tokens&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained('bert-base-cased')
print(tokenizer('Hello world')['input_ids'])

```

From [custom_tokenizers.md](https://huggingface.co/docs/transformers/v5.23.0/en/model_doc/auto)

### NLTK

[GitHub](https://github.com/nltk/nltk) · [PyPI](https://pypi.org/project/nltk) · [Docs](https://www.nltk.org/)

Provides a natural language toolkit.

- Downloads / mo: 48.7M
- Stars: 14.8K
- Last release: 3.10.4
- License: Apache-2.0
- Capabilities: [From the NLTK docs](https://www.nltk.org/)

```sh
python -m pip install nltk
```

**sloria/TextBlob** (9.6K stars)

[sloria/TextBlob](https://github.com/sloria/TextBlob) 

```python
def tokenize(self, text, include_punc=True):
    """Return a list of word tokens.

    :param text: string of text.
    :param include_punc: (optional) whether to
        include punctuation as separate tokens. Default to True.
    """
    tokens = nltk.tokenize.word_tokenize(text)
    if include_punc:
        return tokens
    else:
        # Return each word token
        # Strips punctuation unless the word comes from a contraction
        # e.g. "Let's" => ["Let", "'s"]
        # e.g. "Can't" => ["Ca", "n't"]
        # e.g. "home." => ['home']
        return [
            word if word.startswith("'") else strip_punc(word, all=False)
            for word in tokens
            if strip_punc(word, all=False)
        ]
```

[src/textblob/tokenizers.py](https://github.com/sloria/TextBlob/blob/e496077fb8fd127b3c841cd192d16677e1fde960/src/textblob/tokenizers.py#L27-L47) · [More projects using NLTK →](https://dashboard.exa.ai/playground/search?q=nltk%20GitHub%20projects)

**Quickstart**

```python
from nltk.tokenize import wordpunct_tokenize
print(wordpunct_tokenize('Hello, world!'))

```

From [nltk.tokenize.html](https://www.nltk.org/api/nltk.tokenize.html)

### SentencePiece

[GitHub](https://github.com/google/sentencepiece) · [PyPI](https://pypi.org/project/sentencepiece) · [Docs](https://pypi.org/project/sentencepiece/)

Trains and applies subword tokenization directly to raw text.

- Downloads / mo: 29.8M
- Stars: 12.2K
- Last release: 0.2.3
- License: Apache-2.0
- Capabilities: [From the SentencePiece docs](https://pypi.org/project/sentencepiece/)

**Strengths**

- **Trains directly from raw text.** Train a vocabulary without a language-specific word splitter.
- **Supports sampled segmentations.** Sample different subword splits while preparing training text.

**Watch out for**

- **Normalization can change whitespace.** Check the model’s whitespace rules before assuming exact text reconstruction.

```sh
python -m pip install sentencepiece
```

**NVIDIA-NeMo/Speech** (18.8K stars)

[NVIDIA-NeMo/Speech](https://github.com/NVIDIA-NeMo/Speech) 

```python
def __init__(
    self,
    model_path: str,
    special_tokens: Optional[Union[Dict[str, str], List[str]]] = None,
    legacy: bool = False,
    ignore_extra_whitespaces: bool = True,
    chat_template: Optional[Dict] = None,
    trim_spm_separator_after_special_token=True,
    spm_separator='▁',
):
    self.chat_template = chat_template
    if not model_path or not os.path.exists(model_path):
        raise ValueError(f"model_path: {model_path} is invalid")
    self.tokenizer = sentencepiece.SentencePieceProcessor()
    self.tokenizer.Load(model_path)

    self.original_vocab_size = self.tokenizer.get_piece_size()
    self.vocab_size = self.tokenizer.get_piece_size()
    self.legacy = legacy
    self.ignore_extra_whitespaces = ignore_extra_whitespaces
    # using special symbol for extra_space token, so it is not likely to be in the vocabulary
    self.extra_space_token = '☯'
    self.special_token_to_id = {}
    self.id_to_special_token = {}
    self.trim_spm_separator_after_special_token = trim_spm_separator_after_special_token
    self.spm_separator = spm_separator
    self.spm_separator_id = self.tokenizer.piece_to_id(spm_separator)

    if special_tokens:
        if not self.legacy:
            raise ValueError(
                "Special tokens must be None when legacy is set to False. Provide special tokens at train time."
            )
        self.add_special_tokens(special_tokens)

    self.removed_extra_spaces = self.tokenizer.encode_as_pieces('x  y') == self.tokenizer.encode_as_pieces('x y')
    self.space_sensitive = self.text_to_tokens('x y') != self.text_to_tokens('x') + self.text_to_tokens('y')
    self._var_bpe_extension: VarBPEExtension | None = None  # lazy init
    self._var_bpe_extension_case_insensitive: VarBPEExtension | None = None  # lazy init
```

[nemo/collections/common/tokenizers/sentencepiece_tokenizer.py](https://github.com/NVIDIA-NeMo/Speech/blob/3fce68a9ead4f2e47381a09378848b33bdf70553/nemo/collections/common/tokenizers/sentencepiece_tokenizer.py#L141-L179) · [More projects using SentencePiece →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20sentencepiece%20to%20encode%2C%20decode%20and%20prepare%20model%20tokens&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import sentencepiece as spm
processor = spm.SentencePieceProcessor(model_file='test/botchan_en_unigram_1000.model')
print(processor.encode('This is a test'))

```

From [README.md](https://pypi.org/pypi/sentencepiece/0.2.3/json#info.description)

### spaCy

[GitHub](https://github.com/explosion/spaCy) · [PyPI](https://pypi.org/project/spacy) · [Docs](https://pypi.org/project/spacy/)

Processes natural language in Python.

- Downloads / mo: 25.2M
- Stars: 34.1K
- Last release: 3.8.18
- License: MIT
- Capabilities: [From the spaCy docs](https://pypi.org/project/spacy/)

```sh
python -m pip install spacy
```

**Quickstart**

```python
import spacy
nlp = spacy.blank('en')
print([token.text for token in nlp.tokenizer('Hello, world!')])

```

From [README.md](https://spacy.io/api/tokenizer) · [Find projects using spaCy →](https://dashboard.exa.ai/playground/search?q=spacy%20GitHub%20projects)

### Sentence Transformers

[GitHub](https://github.com/huggingface/sentence-transformers) · [PyPI](https://pypi.org/project/sentence-transformers) · [Docs](https://pypi.org/project/sentence-transformers/)

Computes embeddings for retrieval and reranking.

- Downloads / mo: 22.8M
- Stars: 19.3K
- Last release: 6.3.0
- License: Apache-2.0
- Capabilities: [From the Sentence Transformers docs](https://pypi.org/project/sentence-transformers/)

```sh
python -m pip install sentence-transformers
```

**langchain-ai/langchain** (149.7K stars)

[langchain-ai/langchain](https://github.com/langchain-ai/langchain) 

```python
def __init__(
    self,
    chunk_overlap: int = 50,
    model_name: str = "sentence-transformers/all-mpnet-base-v2",
    tokens_per_chunk: int | None = None,
    model_kwargs: dict[str, Any] | None = None,
    **kwargs: Any,
) -> None:
    """Create a new `TextSplitter`.

    Args:
        chunk_overlap: The number of tokens to overlap between chunks.
        model_name: The name of the sentence transformer model to use.
        tokens_per_chunk: The number of tokens per chunk.

            If `None`, uses the maximum tokens allowed by the model.
        model_kwargs: Additional parameters for model initialization.
            Parameters of sentence_transformers.SentenceTransformer can be used.

    Raises:
        ImportError: If the `sentence_transformers` package is not installed.
        ValueError: If `tokens_per_chunk` exceeds the model's maximum token limit.
    """
    super().__init__(**kwargs, chunk_overlap=chunk_overlap)

    try:
        sentence_transformers = cast("Any", import_module("sentence_transformers"))
        sentence_transformer_cls = sentence_transformers.SentenceTransformer
    except ImportError as err:
        msg = (
            "Could not import sentence_transformers python package. "
            "This is needed in order to use SentenceTransformersTokenTextSplitter. "
            "Please install it with `pip install sentence-transformers`."
        )
        raise ImportError(msg) from err

    self.model_name = model_name
    self._model = sentence_transformer_cls(self.model_name, **(model_kwargs or {}))
    self.tokenizer = self._model.tokenizer
    self._initialize_chunk_configuration(tokens_per_chunk=tokens_per_chunk)
```

[libs/text-splitters/langchain_text_splitters/sentence_transformers.py](https://github.com/langchain-ai/langchain/blob/80655a182f24002f78f6baf884a67e227c06d7fa/libs/text-splitters/langchain_text_splitters/sentence_transformers.py#L16-L55) · [More projects using Sentence Transformers →](https://dashboard.exa.ai/playground/search?q=sentence-transformers%20GitHub%20projects)

**Quickstart**

```python
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
features = model.preprocess(['Hello world'])
print(features)

```

From [SentenceTransformer.html#sentence_transformers.SentenceTransformer.tokenize](https://sbert.net/docs/package_reference/sentence_transformer/SentenceTransformer.html#sentence_transformers.SentenceTransformer.tokenize)

### Jieba

[GitHub](https://github.com/fxsjy/jieba) · [PyPI](https://pypi.org/project/jieba) · [Docs](https://pypi.org/project/jieba/)

Segments Chinese text into words.

- Downloads / mo: 6.2M
- Stars: 35.2K
- Last release: 0.42.1
- License: MIT
- Capabilities: [From the Jieba docs](https://pypi.org/project/jieba/)

```sh
python -m pip install jieba
```

**PaddlePaddle/PaddleNLP** (13.0K stars)

[PaddlePaddle/PaddleNLP](https://github.com/PaddlePaddle/PaddleNLP) 

```python
def cut(self, sentence, cut_all=False, use_hmm=True):
    """
    The method used to cut the text to tokens.

    Args:
        sentence(str): The text that needs to be cut.
        cut_all(bool, optional): Whether to use the full mode. If True,
            using full mode that gets all the possible words from the
            sentence, which is fast but not accurate. If False, using
            accurate mode that attempts to cut the sentence into the most
            accurate segmentations, which is suitable for text analysis.
            Default: False.
        use_hmm(bool, optional): Whether to use the HMM model. Default: True.

    Returns:
        list[str]: A list of tokens.

    Example:
        .. code-block:: python

            from paddlenlp.data import Vocab, JiebaTokenizer
            # The vocab file. The sample file can be downloaded firstly.
            # wget https://bj.bcebos.com/paddlenlp/data/senta_word_dict.txt
            vocab_file_path = './senta_word_dict.txt'
            # Initialize the Vocab
            vocab = Vocab.load_vocabulary(
                vocab_file_path,
                unk_token='[UNK]',
                pad_token='[PAD]')
            tokenizer = JiebaTokenizer(vocab)

            tokens = tokenizer.cut('我爱你中国')
            print(tokens)
            # ['我爱你', '中国']
    """
    return self.tokenizer.lcut(sentence, cut_all, use_hmm)
```

[paddlenlp/data/tokenizer.py](https://github.com/PaddlePaddle/PaddleNLP/blob/3f87dac9b719f75399f92f8bf634ae2ef0611832/paddlenlp/data/tokenizer.py#L56-L91) · [More projects using Jieba →](https://dashboard.exa.ai/playground/search?q=jieba%20GitHub%20projects)

**Quickstart**

```python
import jieba
print(jieba.lcut('我来到北京清华大学'))

```

From [README.md](https://raw.githubusercontent.com/fxsjy/jieba/master/README.md)

## FAQ

### Which Python tokenizer library should I use?

[tiktoken](#tiktoken) suits counting and encoding tokens for OpenAI models. [Tokenizers](#tokenizers) and [SentencePiece](#sentencepiece) suit training a custom vocabulary. [Transformers](#transformers) suits loading the tokenizer that matches a specific model.

### What is tiktoken?

[tiktoken](#tiktoken) encodes and decodes text with byte-pair tokenization for OpenAI models. It can select the encoding for a given model name.

### What is SentencePiece?

[SentencePiece](#sentencepiece) trains and applies subword tokenization directly on raw sentences.

### What is Jieba?

[Jieba](#jieba) segments Chinese text into words.

### Why does tiktoken raise an error on special-token text?

Encoding raises by default for text that matches a special token. The allowed_special and disallowed_special parameters control that behavior.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python tokenizer libraries tiktoken Hugging Face Tokenizers SentencePiece Transformers code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
