# Python NLP libraries

Python NLP (natural language processing) libraries split text into words and sentences, label them, and turn them into numbers that models can use. These libraries handle the text steps inside search engines, document tagging, and the embedding step of retrieval for AI agents.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [Transformers](#transformers) | 119.8M | 169.2K | Nov 2026 | Apache 2.0 License |
| [NLTK](#nltk) | 48.3M | 14.8K | Oct 2026 | Apache License, Version 2.0 |
| [spaCy](#spacy) | 25.0M | 34.0K | Oct 2026 | MIT |
| [Sentence Transformers](#sentence-transformers) | 22.6M | 19.3K | Nov 2026 | Apache-2.0 |
| [Jieba](#jieba) | 6.2M | 35.2K | Jan 2020 | MIT |
| [TextBlob](#textblob) | 3.2M | 9.6K | Jul 2026 | MIT |
| [Gensim](#gensim) | 3.0M | 16.5K | Oct 2025 | LGPL-2.1-only |
| [fastText](#fasttext) | 2.2M | 26.5K | Jun 2024 | MIT |

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

[NLTK](#nltk) has the most monthly downloads in this comparison, at 42.0M.

## Capabilities

| Library | Text classifier training | Linguistic token labels |
| --- | --- | --- |
| [Transformers](#transformers) | Yes | Yes |
| [NLTK](#nltk) | Yes | Yes |
| [spaCy](#spacy) | Yes | Yes |
| [Sentence Transformers](#sentence-transformers) | Yes | No |
| [Jieba](#jieba) | Undocumented | Yes |
| [TextBlob](#textblob) | Yes | Yes |
| [Gensim](#gensim) | No | No |
| [fastText](#fasttext) | Yes | No |

## Libraries

### Transformers

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

Transformers loads pretrained language models from the Hugging Face Hub and runs them for tasks such as text classification. `pipeline` pairs a model with its tokenizer. One call on a sentence returns a label and a score. Fine-tuning uses the same model classes, and training frameworks and inference engines reuse the model definitions. The library runs on PyTorch.

- Downloads / mo: 119.8M
- Stars: 169.2K
- Last release: 5.23.0
- License: Apache 2.0 License
- Capabilities: [From the Transformers docs](https://huggingface.co/docs/transformers/)

**Strengths**

- **Models by name.** A task and a model name from the Hub are enough for `pipeline` to download and run a model.

**Watch out for**

- **Weights download on first use.** Each model fetches its weights the first time it loads, and large models need a GPU with enough memory to hold them.

```sh
pip install torch transformers
```

**deepset-ai/haystack** (27.0K stars)

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

```python
def run(self, text: str) -> dict[str, str]:
    """
    Routes the text strings to different connections based on a category label.

    :param text: A string of text to route.
    :returns:
        A dictionary with the label as key and the text as value.

    :raises TypeError:
        If the input is not a str.
    :raises RuntimeError:
        If the pipeline has not been loaded because warm_up() was not called before.
    """
    if self.pipeline is None:
        raise RuntimeError(
            "The component TransformersZeroShotTextRouter wasn't warmed up. Run 'warm_up()' before calling 'run()'."
        )

    if not isinstance(text, str):
        raise TypeError("TransformersZeroShotTextRouter expects a str as input.")

    prediction = self.pipeline([text], candidate_labels=self.labels, multi_label=self.multi_label)
    predicted_scores = prediction[0]["scores"]
    max_score_index = max(range(len(predicted_scores)), key=predicted_scores.__getitem__)
    label = prediction[0]["labels"][max_score_index]
    return {label: text}

```

[haystack/components/routers/zero_shot_text_router.py](https://github.com/deepset-ai/haystack/blob/dc1d72228adeaac8e657d3a4946c3e246d45784d/haystack/components/routers/zero_shot_text_router.py#L192-L217) · [More projects using Transformers →](https://dashboard.exa.ai/playground/search?q=transformers%20GitHub%20projects)

**Quickstart**

```python
from transformers import pipeline

classifier = pipeline(model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
classifier("This movie is disgustingly good !")

```

From [text_classification.py](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/pipelines/text_classification.py)

### NLTK

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

NLTK, the Natural Language Toolkit, is a suite of Python modules, data sets, and tutorials for natural language processing research and development. `nltk.word_tokenize` splits text into words, and other modules tag parts of speech, parse sentences, chunk named entities, and classify text. Corpora and lexical resources download separately with `nltk.download`.

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

**Strengths**

- **Offers a broad algorithm toolkit.** Choose tokenization, tagging, parsing, and classification tools alongside corpus resources.
- **Extracts named entity chunks.** Run the named-entity chunker on already tagged tokens.

**Watch out for**

- **Resources download separately.** Tokenizer models, taggers, and corpora each need `nltk.download` before first use.

```sh
pip install --user -U nltk
```

**miso-belica/sumy** (3.7K stars)

[miso-belica/sumy](https://github.com/miso-belica/sumy) 

```python
def _get_sentence_tokenizer(self, language):
    if language in self.SPECIAL_SENTENCE_TOKENIZERS:
        return self.SPECIAL_SENTENCE_TOKENIZERS[language]
    try:
        return nltk.tokenize.PunktTokenizer(language)
    except (LookupError, zipfile.BadZipfile) as e:
        raise LookupError(
            "NLTK tokenizers are missing or the language is not supported.\n"
            """Download them by following command: python -c "import nltk; nltk.download('punkt_tab')"\n"""
            "Original error was:\n" + str(e)
        )

```

[sumy/nlp/tokenizers.py](https://github.com/miso-belica/sumy/blob/37837583eaa6686e14241c28ef7fdea1369879f6/sumy/nlp/tokenizers.py#L196-L206) · [More projects using NLTK →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20that%20use%20nltk&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 nltk
sentence = """At eight o'clock on Thursday morning
Arthur didn't feel very good."""
tokens = nltk.word_tokenize(sentence)
print(tokens)

```

From [index.rst](https://www.nltk.org/)

### spaCy

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

spaCy processes text through a pipeline of components that tokenize, tag parts of speech, parse dependencies, recognize named entities, and classify text. `spacy.load` loads a trained pipeline such as `en_core_web_sm`, and calling it on a string returns a `Doc` that holds every token and its labels. Pipelines can include pretrained transformers such as BERT, and spaCy supports tokenization and training for more than seventy languages.

- Downloads / mo: 25.0M
- Stars: 34.0K
- Last release: 3.8.18
- License: MIT
- Capabilities: [From the spaCy docs](https://spacy.io/)

**Strengths**

- **Combines linguistic pipeline components.** Process text with trained tagging, parsing, and entity-recognition components.
- **Serializes annotated documents as JSON.** Export token-level annotations through the document JSON API.

**Watch out for**

- **Labels need a trained pipeline.** Statistical tags and entities come from a trained pipeline, which installs as a separate package.

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

**medspacy/medspacy** (688 stars)

[medspacy/medspacy](https://github.com/medspacy/medspacy) 

```python
def load(
    model: Union[Literal["default"], str, Language] = "default",
    medspacy_enable: Union[Literal["all", "default"], Iterable[str]] = "default",
    medspacy_disable: Optional[Iterable[str]] = None,
    language_code: str = "en",
    load_rules: bool = True,
    quickumls_path: Optional[str] = None,
    **model_kwargs,
):
    """Load a spaCy language object with medSpaCy pipeline components.
    By default, the base model will be a blank 'en' model with the
    following components:
        - "medspacy_tokenizer": A customized, more aggressive tokenizer than the default spaCy tokenizer. This is set to
            `nlp.tokenizer` and is not loaded as a pipeline component.
        - "medspacy_pyrush": PyRuSH Sentencizer for sentence splitting
        - "medspacy_target_matcher": TargetMatcher for extended pattern matching
        - "medspacy_context": ConText for attribute assertion
        - "medspacy_quickumls": QuickUMLS for UMLS concept mapping
    Args:
        model: The base spaCy model to load. If 'default', will instantiate from a blank 'en' model. If it is a spaCy
            language model, then it will simply add medspaCy components to the existing pipeline. If it is a string
            other than 'default', passes the string to spacy.load(model, **model_kwargs).
        medspacy_enable: Specifies which components to enable in the medspacy pipeline. If "default", will load all components
            found in `DEFAULT_PIPE_NAMES`. These represent the simplest components used in a clinical NLP pipeline:
            tokenization, sentence detection, concept identification, and ConText. If "all", all components in medspaCy
            will be loaded. If a collection of strings, the components specified will be loaded.
        medspacy_disable: A collection of component names to exclude. Requires "all" is the value for `enable`.
        language_code: Language code to use (ISO code) as a default for loading additional resources.  See documentation
            and also the /resources directory to see which resources might be available in each language.
            Default is "en" for English.
        load_rules: Whether to include default rules for available components. If True, sectionizer and context will
            both be loaded with default rules. Default is True.
        quickumls_path: Path to QuickUMLS dictionaries if it is included in the pipeline.
        model_kwargs: Optional model keyword arguments to pass to spacy.load().

    Returns:
        A spaCy Language object containing the specified medspacy components.
    """

    medspacy_enable, medspacy_disable = _build_pipe_names(
        medspacy_enable, medspacy_disable
    )

    if model == "default":
        nlp = spacy.blank("en")
    elif isinstance(model, Language):
        nlp = model
    elif isinstance(model, str):
        nlp = spacy.load(model, **model_kwargs)
    else:
        raise ValueError(
            "model must be either 'default' or an actual spaCy Language object, not ",
            type(model),
        )

    if "medspacy_tokenizer" in medspacy_enable:
        from .custom_tokenizer import create_medspacy_tokenizer

        medspacy_tokenizer = create_medspacy_tokenizer(nlp)
        nlp.tokenizer = medspacy_tokenizer

    if "medspacy_preprocessor" in medspacy_enable:
        from .preprocess import Preprocessor

        preprocessor = Preprocessor(nlp.tokenizer)
        nlp.tokenizer = preprocessor

    if "medspacy_pyrush" in medspacy_enable:
        pyrush_path = path.join(
            Path(__file__).resolve().parents[1], "resources", language_code.lower(), "rush_rules.tsv"
        )
        nlp.add_pipe("medspacy_pyrush", config={"rules_path": pyrush_path})

    if "medspacy_target_matcher" in medspacy_enable:
        nlp.add_pipe("medspacy_target_matcher")

    if "medspacy_quickumls" in medspacy_enable:
        if quickumls_path is None:
            quickumls_path = get_quickumls_demo_dir(language_code)

            logger.info(
                "Loading QuickUMLS resources from a Medspacy-distributed SAMPLE of UMLS data from here: {}".format(
                    quickumls_path
                )
            )

        nlp.add_pipe("medspacy_quickumls", config={"quickumls_fp": quickumls_path})

    if "medspacy_context" in medspacy_enable:
        if load_rules is True:
            config = {'language_code': language_code}
        else:
            config = {"rules": None,
                      'language_code': language_code}
        nlp.add_pipe("medspacy_context", config=config)

    if "medspacy_sectionizer" in medspacy_enable:
        if load_rules is True:
            config = {'language_code': language_code}
        else:
            config = {"rules": None,
                      'language_code': language_code}
        nlp.add_pipe("medspacy_sectionizer", config=config)

    if "medspacy_postprocessor" in medspacy_enable:
        nlp.add_pipe("medspacy_postprocessor")

    if "medspacy_doc_consumer" in medspacy_enable:
        nlp.add_pipe("medspacy_doc_consumer")

    return nlp

```

[medspacy/util.py](https://github.com/medspacy/medspacy/blob/b7bb7d82f2e8fbadc9ab26d6b4c37578f8883c2c/medspacy/util.py#L37-L147) · [More projects using spaCy →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20that%20use%20spacy&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 spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("This is a sentence.")
print([(w.text, w.pos_) for w in doc])

```

From [models.mdx](https://spacy.io/usage/models)

### Sentence Transformers

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

Sentence Transformers computes embeddings, vectors that place texts with similar meaning close together, using pretrained models from Hugging Face. `SentenceTransformer` loads a model, `encode` turns a list of sentences into embeddings, and `similarity` compares them. Cross-encoder models score pairs of texts for reranking, and sparse encoder models produce sparse embeddings. The same library trains and fine-tunes these models.

- Downloads / mo: 22.6M
- Stars: 19.3K
- Last release: 6.3.0
- License: Apache-2.0
- Capabilities: [From the Sentence Transformers docs](https://sbert.net/)

**Strengths**

- **Pretrained models by name.** More than fifteen thousand pretrained models on Hugging Face load by name.

**Watch out for**

- **Models download on first use.** Each model downloads from Hugging Face the first time it loads.

```sh
pip install -U sentence-transformers
```

**chroma-core/chroma** (29.7K stars)

[chroma-core/chroma](https://github.com/chroma-core/chroma) 

```python
def __call__(self, input: Documents) -> Embeddings:
    """Generate embeddings for the given documents.

    Args:
        input: Documents to generate embeddings for.

    Returns:
        Embeddings for the documents.
    """
    embeddings = self._model.encode(
        list(input),
        convert_to_numpy=True,
        normalize_embeddings=self.normalize_embeddings,
    )

    return [np.array(embedding, dtype=np.float32) for embedding in embeddings]

```

[chromadb/utils/embedding_functions/sentence_transformer_embedding_function.py](https://github.com/chroma-core/chroma/blob/1a3ac2c7c623adbd03ed2508dc27b98cdf26016d/chromadb/utils/embedding_functions/sentence_transformer_embedding_function.py#L53-L68) · [More projects using Sentence Transformers →](https://dashboard.exa.ai/playground/search?q=sentence-transformers%20GitHub%20projects)

**Quickstart**

```python
from sentence_transformers import SentenceTransformer

# 1. Load a pretrained Sentence Transformer model
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")

# The sentences to encode
sentences = [
    "The weather is lovely today.",
    "It's so sunny outside!",
    "He drove to the stadium.",
]

# 2. Calculate embeddings by calling model.encode()
embeddings = model.encode(sentences)

```

From [quickstart.rst](https://www.sbert.net/docs/quickstart.html)

### Jieba

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

Jieba segments Chinese text into words, which Chinese writing does not separate with spaces. `jieba.cut` runs in accurate mode by default, full mode lists every possible word, and search engine mode splits long words again to improve recall. Custom dictionaries add domain terms, and the segmenter also handles Traditional Chinese.

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

**Strengths**

- **Custom dictionaries.** A user dictionary adds names and terms that the default dictionary misses.

**Watch out for**

- **Paddle mode needs PaddlePaddle.** The deep learning mode requires the separate paddlepaddle-tiny package.

```sh
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
seg_list = jieba.cut("我来到北京清华大学", cut_all=False)
print("Default Mode: " + "/ ".join(seg_list))  # 精确模式

```

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

### TextBlob

[GitHub](https://github.com/sloria/TextBlob) · [PyPI](https://pypi.org/project/textblob) · [Docs](https://textblob.readthedocs.io/)

TextBlob wraps NLTK and pattern in a single object for common text tasks. `TextBlob(text)` exposes part-of-speech tags, noun phrases, sentences, and a sentiment score with polarity and subjectivity. The library also tokenizes text and trains Naive Bayes and decision tree classifiers.

- Downloads / mo: 3.2M
- Stars: 9.6K
- Last release: 0.20.1
- License: MIT
- Capabilities: [From the TextBlob docs](https://textblob.readthedocs.io/)

**Strengths**

- **One object for common tasks.** Tags, noun phrases, and sentiment come from attributes on the same `TextBlob` object.

**Watch out for**

- **Built on NLTK data.** TextBlob relies on NLTK corpora, which download separately before first use.

```sh
pip install -U textblob
python -m textblob.download_corpora
```

**Roibal/Cryptocurrency-Trading-Bots-Python-Beginner-Advance** (1.4K stars)

[Roibal/Cryptocurrency-Trading-Bots-Python-Beginner-Advance](https://github.com/Roibal/Cryptocurrency-Trading-Bots-Python-Beginner-Advance) 

```python
def get_tweet_sentiment(self, tweet):
    '''
    Utility function to classify sentiment of passed tweet
    using textblob's sentiment method
    '''
    # create TextBlob object of passed tweet text
    analysis = TextBlob(self.clean_tweet(tweet))
    # set sentiment
    if analysis.sentiment.polarity > 0:
        return 'positive'
    elif analysis.sentiment.polarity == 0:
        return 'neutral'
    else:
        return 'negative'

```

[Crypto-Trading-Bots/Crypto_Sentiment_Analysis_SocialMedia_Bot.py](https://github.com/Roibal/Cryptocurrency-Trading-Bots-Python-Beginner-Advance/blob/6cd9f639ac7f9d914d556738ca3aeeef53618146/Crypto-Trading-Bots/Crypto_Sentiment_Analysis_SocialMedia_Bot.py#L79-L92) · [More projects using TextBlob →](https://dashboard.exa.ai/playground/search?q=textblob%20GitHub%20projects)

**Quickstart**

```python
from textblob import TextBlob
testimonial = TextBlob("Textblob is amazingly simple to use. What great fun!")
print(testimonial.sentiment)

```

From [quickstart.rst](https://textblob.readthedocs.io/en/dev/quickstart.html)

### Gensim

[GitHub](https://github.com/piskvorky/gensim) · [PyPI](https://pypi.org/project/gensim) · [Docs](https://radimrehurek.com/gensim/)

Gensim builds topic models and word vectors from large collections of documents. Its algorithms, including word vector training, LDA, and LSA, stream documents from disk, so a corpus larger than RAM can be processed. `gensim.downloader` loads pretrained vectors such as GloVe by name, and `most_similar` returns the nearest words. LSA and LDA can also run on a cluster of computers.

- Downloads / mo: 3.0M
- Stars: 16.5K
- Last release: 4.4.0
- License: LGPL-2.1-only
- Capabilities: [From the Gensim docs](https://radimrehurek.com/gensim/)

**Strengths**

- **Fits unsupervised semantic models.** Train topic and word-vector models from a corpus of documents.
- **Streams corpora from disk.** Iterate over corpus documents without loading the entire matrix into memory.

**Watch out for**

- **Features must match training.** New documents need the same preprocessing and dictionary as the training corpus.
- **Maintenance mode.** Gensim accepts bug and documentation fixes but takes no new features.

```sh
pip install --upgrade gensim
```

**MIND-Lab/OCTIS** (807 stars)

[MIND-Lab/OCTIS](https://github.com/MIND-Lab/OCTIS) 

```python
def train_model(self, dataset, hyperparams=None, top_words=10):
    """
    Train the model and return output

    Parameters
    ----------
    dataset : dataset to use to build the model
    hyperparams : hyperparameters to build the model
    top_words : if greater than 0 returns the most significant words for
                each topic in the output (Default True)
    Returns
    -------
    result : dictionary with up to 3 entries,
             'topics', 'topic-word-matrix' and
             'topic-document-matrix'
    """
    if hyperparams is None:
        hyperparams = {}

    if self.use_partitions:
        train_corpus, test_corpus = dataset.get_partitioned_corpus(
            use_validation=False)
    else:
        train_corpus = dataset.get_corpus()

    if self.id2word is None:
        self.id2word = corpora.Dictionary(dataset.get_corpus())

    if self.id_corpus is None:
        self.id_corpus = [self.id2word.doc2bow(document)
                          for document in train_corpus]

    if "num_topics" not in hyperparams:
        hyperparams["num_topics"] = self.hyperparameters["num_topics"]

    # Allow alpha to be a float in case of symmetric alpha
    if "alpha" in hyperparams:
        if isinstance(hyperparams["alpha"], float):
            hyperparams["alpha"] = [
                hyperparams["alpha"]
            ] * hyperparams["num_topics"]

    hyperparams["corpus"] = self.id_corpus
    hyperparams["id2word"] = self.id2word
    self.hyperparameters.update(hyperparams)

    self.trained_model = ldamodel.LdaModel(**self.hyperparameters)

    result = {}

    result["topic-word-matrix"] = self.trained_model.get_topics()

    if top_words > 0:
        topics_output = []
        for topic in result["topic-word-matrix"]:
            top_k = np.argsort(topic)[-top_words:]
            top_k_words = list(reversed([self.id2word[i] for i in top_k]))
            topics_output.append(top_k_words)
        result["topics"] = topics_output

    result["topic-document-matrix"] = self._get_topic_document_matrix()

    if self.use_partitions:
        new_corpus = [self.id2word.doc2bow(
            document) for document in test_corpus]
        if self.update_with_test:
            self.trained_model.update(new_corpus)
            self.id_corpus.extend(new_corpus)

            result["test-topic-word-matrix"] = (
                self.trained_model.get_topics())

            if top_words > 0:
                topics_output = []
                for topic in result["test-topic-word-matrix"]:
                    top_k = np.argsort(topic)[-top_words:]
                    top_k_words = list(
                        reversed([self.id2word[i] for i in top_k]))
                    topics_output.append(top_k_words)
                result["test-topics"] = topics_output

            result["test-topic-document-matrix"] = (
                self._get_topic_document_matrix())

        else:
            test_document_topic_matrix = []
            for document in new_corpus:
                document_topics_tuples = self.trained_model[document]
                document_topics = np.zeros(
                    self.hyperparameters["num_topics"])
                for single_tuple in document_topics_tuples:
                    document_topics[single_tuple[0]] = single_tuple[1]

                test_document_topic_matrix.append(document_topics)
            result["test-topic-document-matrix"] = np.array(
                test_document_topic_matrix).transpose()
    return result

```

[octis/models/LDA.py](https://github.com/MIND-Lab/OCTIS/blob/8f9a0ac5a12e3b72ecd77dcba4f181c77e4595f1/octis/models/LDA.py#L149-L245) · [More projects using Gensim →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20that%20use%20gensim&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 gensim.downloader as api
model = api.load("glove-wiki-gigaword-50")
model.most_similar("glass")

```

From [run_downloader_api.html](https://radimrehurek.com/gensim/auto_examples/howtos/run_downloader_api.html)

### fastText

[GitHub](https://github.com/facebookresearch/fastText) · [PyPI](https://pypi.org/project/fasttext) · [Docs](https://fasttext.cc/)

fastText learns word representations and trains text classifiers. `fasttext.train_unsupervised` learns word vectors from a text file, and `fasttext.train_supervised` trains a classifier from lines that start with `__label__` tags. Vectors are built from character n-grams, so words outside the training vocabulary still get a vector.

- Downloads / mo: 2.2M
- Stars: 26.5K
- Last release: 0.9.3
- License: MIT
- Capabilities: [From the fastText docs](https://fasttext.cc/)

**Strengths**

- **Pretrained word vectors.** Facebook publishes word vectors for a hundred and fifty-seven languages, trained on Wikipedia and Common Crawl.
- **Language identification.** A downloadable model identifies the language of a text.

**Watch out for**

- **Compiled during install.** The package compiles C++ code when it installs and builds on macOS and Linux.

```sh
pip install fasttext
```

**mlfoundations/dclm** (1.5K stars)

[mlfoundations/dclm](https://github.com/mlfoundations/dclm) 

```python
def main():
    args = get_args()
    random.seed(args.seed)
    train_input = args.input

    train_was_split = False
    if args.valid_input:
        valid_input = args.valid_input
    elif args.valid_frac > 0:
        train_input, valid_input = split_train_val(train_input, args.valid_frac)
        train_was_split = True
    else:
        valid_input = None

    hyperparams = {'lr': args.lr, 'dim': args.dim, 'ws': args.ws, 'epoch': args.epoch, 'minCount': args.minCount, 'wordNgrams': args.wordNgrams}
    model = fasttext.train_supervised(input=train_input, **hyperparams)

    print("Training results")
    print_results(*model.test(train_input))

    if valid_input is not None:
        print("Validation results")
        print_results(*model.test(valid_input))

    # Save the model
    output = args.name if args.name.endswith(".bin") else args.name + ".bin"
    model.save_model(os.path.join(args.output_dir, output))

    if train_was_split:
        os.remove(train_input)
        os.remove(valid_input)

```

[baselines/train_fasttext_classifier.py](https://github.com/mlfoundations/dclm/blob/361714bdd60bb9b7f4b2d8354cebbf0dec0c329e/baselines/train_fasttext_classifier.py#L55-L85) · [More projects using fastText →](https://dashboard.exa.ai/playground/search?q=fasttext%20GitHub%20projects)

**Quickstart**

```python
import fasttext
model = fasttext.train_supervised('data.train.txt')

```

From [python-module.md](https://fasttext.cc/docs/en/python-module.html)

## FAQ

### Which Python NLP library should I use?

For a pipeline that tags, parses, and finds entities, [spaCy](#spacy) loads a trained pipeline in one call. [NLTK](#nltk) collects many separate algorithms and corpora for research and teaching. For embeddings and semantic search, [Sentence Transformers](#sentence-transformers) encodes text with pretrained models, and [Transformers](#transformers) runs pretrained models for classification and other tasks.

### What is Sentence Transformers?

[Sentence Transformers](#sentence-transformers) computes embeddings, vectors that place similar texts close together, with pretrained models from Hugging Face. `model.encode` turns a list of sentences into embeddings, and cross-encoder models score pairs of texts for reranking. Uses include semantic search, semantic textual similarity, and paraphrase mining.

### NLTK vs spaCy: which should I use?

NLTK is a toolkit of separate algorithms, corpora, and lexical resources, each downloaded as needed. spaCy runs text through one pipeline of trained components that tags, parses, and labels entities, and returns a `Doc` object holding every annotation.

### What are spaCy models?

spaCy's trained pipelines are packages, such as `en_core_web_sm`, installed with `spacy download` and loaded with `spacy.load`. Statistical tags and entities come from these pipelines, and spaCy supports tokenization and training for more than seventy languages.

### How do I use word vectors with Gensim?

[Gensim](#gensim) trains word vector models on documents streamed from disk, so the corpus can be larger than memory. Pretrained vectors such as GloVe load by name through `gensim.downloader`, and `most_similar` returns the nearest words.

## How this page was built

Data checked Nov 19, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Python NLP libraries spaCy NLTK Gensim Stanza tokenization POS named entities topic modeling code examples",
    "numResults": 5
  }
}
```

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