Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
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
NLTK has the most monthly downloads in this comparison, at 42.0M.
Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.
Libraries and code examples
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
Strengths
Models by name.A task and a model name from the Hub are enough for pipeline to download and run a model.
Limitations
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.
from transformers import pipeline
classifier = pipeline(model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
classifier("This movie is disgustingly good !")
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}
NLTK
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
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.
Limitations
Resources download separately.Tokenizer models, taggers, and corpora each need nltk.download before first use.
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)
)
spaCy
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
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.
Limitations
Labels need a trained pipeline.Statistical tags and entities come from a trained pipeline, which installs as a separate package.
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
Sentence Transformers
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
Strengths
Pretrained models by name.More than fifteen thousand pretrained models on Hugging Face load by name.
Limitations
Models download on first use.Each model downloads from Hugging Face the first time it loads.
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)
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]
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
Strengths
Custom dictionaries.A user dictionary adds names and terms that the default dictionary misses.
Limitations
Paddle mode needs PaddlePaddle.The deep learning mode requires the separate paddlepaddle-tiny package.
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)
TextBlob
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
Strengths
One object for common tasks.Tags, noun phrases, and sentiment come from attributes on the same TextBlob object.
Limitations
Built on NLTK data.TextBlob relies on NLTK corpora, which download separately before first use.
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'
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
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.
Limitations
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.
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
fastText
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
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.
Limitations
Compiled during install.The package compiles C++ code when it installs and builds on macOS and Linux.
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)
FAQ
For a pipeline that tags, parses, and finds entities, spaCy loads a trained pipeline in one call. NLTK collects many separate algorithms and corpora for research and teaching. For embeddings and semantic search, Sentence Transformers encodes text with pretrained models, and Transformers runs pretrained models for classification and other tasks.
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 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.
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.
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.
For coding agents
Found your NLP library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.