Text preprocessing, representation and visualization from zero to hero.

Overview

Github stars pip package pip downloads Github issues Github license

Text preprocessing, representation and visualization from zero to hero.

From zero to heroInstallationGetting StartedExamplesAPIFAQContributions

From zero to hero

Texthero is a python toolkit to work with text-based dataset quickly and effortlessly. Texthero is very simple to learn and designed to be used on top of Pandas. Texthero has the same expressiveness and power of Pandas and is extensively documented. Texthero is modern and conceived for programmers of the 2020 decade with little knowledge if any in linguistic.

You can think of Texthero as a tool to help you understand and work with text-based dataset. Given a tabular dataset, it's easy to grasp the main concept. Instead, given a text dataset, it's harder to have quick insights into the underline data. With Texthero, preprocessing text data, mapping it into vectors, and visualizing the obtained vector space takes just a couple of lines.

Texthero include tools for:

  • Preprocess text data: it offers both out-of-the-box solutions but it's also flexible for custom-solutions.
  • Natural Language Processing: keyphrases and keywords extraction, and named entity recognition.
  • Text representation: TF-IDF, term frequency, and custom word-embeddings (wip)
  • Vector space analysis: clustering (K-means, Meanshift, DBSCAN and Hierarchical), topic modeling (wip) and interpretation.
  • Text visualization: vector space visualization, place localization on maps (wip).

Texthero is free, open-source and well documented (and that's what we love most by the way!).

We hope you will find pleasure working with Texthero as we had during his development.

Hablas español? क्या आप हिंदी बोलते हैं? 日本語が話せるのか?

Texthero has been developed for the whole NLP community. We know how hard it is to deal with different NLP tools (NLTK, SpaCy, Gensim, TextBlob, Sklearn): that's why we developed Texthero, to simplify things.

Now, the next main milestone is to provide multilingual support and for this big step, we need the help of all of you. ¿Hablas español? Sie sprechen Deutsch? 你会说中文? 日本語が話せるのか? Fala português? Parli Italiano? Вы говорите по-русски? If yes or you speak another language not mentioned here, then you might help us develop multilingual support! Even if you haven't contributed before or you just started with NLP, contact us or open a Github issue, there is always a first time :) We promise you will learn a lot, and, ... who knows? It might help you find your new job as an NLP-developer!

For improving the python toolkit and provide an even better experience, your aid and feedback are crucial. If you have any problem or suggestion please open a Github issue, we will be glad to support you and help you.

Beta version

Texthero's community is growing fast. Texthero though is still in a beta version; soon, a faster and better version will be released and it will bring some major changes.

For instance, to give a more granular control over the pipeline, starting from the next version on, all preprocessing functions will require as argument an already tokenized text. This will be a major change.

Once released the stable version (Texthero 2.0), backward compatibility will be respected. Until this point, backward compatibility will be present but it will be weaker.

If you want to be part of this fast-growing movements, do not hesitate to contribute: CONTRIBUTING!

Installation

Install texthero via pip:

pip install texthero

☝️ Under the hoods, Texthero makes use of multiple NLP and machine learning toolkits such as Gensim, NLTK, SpaCy and scikit-learn. You don't need to install them all separately, pip will take care of that.

For faster performance, make sure you have installed Spacy version >= 2.2. Also, make sure you have a recent version of python, the higher, the best.

Getting started

The best way to learn Texthero is through the Getting Started docs.

In case you are an advanced python user, then help(texthero) should do the work.

Examples

1. Text cleaning, TF-IDF representation and Visualization

import texthero as hero
import pandas as pd

df = pd.read_csv(
   "https://github.com/jbesomi/texthero/raw/master/dataset/bbcsport.csv"
)

df['pca'] = (
   df['text']
   .pipe(hero.clean)
   .pipe(hero.tfidf)
   .pipe(hero.pca)
)
hero.scatterplot(df, 'pca', color='topic', title="PCA BBC Sport news")

2. Text preprocessing, TF-IDF, K-means and Visualization

import texthero as hero
import pandas as pd

df = pd.read_csv(
    "https://github.com/jbesomi/texthero/raw/master/dataset/bbcsport.csv"
)

df['tfidf'] = (
    df['text']
    .pipe(hero.clean)
    .pipe(hero.tfidf)
)

df['kmeans_labels'] = (
    df['tfidf']
    .pipe(hero.kmeans, n_clusters=5)
    .astype(str)
)

df['pca'] = df['tfidf'].pipe(hero.pca)

hero.scatterplot(df, 'pca', color='kmeans_labels', title="K-means BBC Sport news")

3. Simple pipeline for text cleaning

>>> import texthero as hero
>>> import pandas as pd
>>> text = "This sèntencé    (123 /) needs to [OK!] be cleaned!   "
>>> s = pd.Series(text)
>>> s
0    This sèntencé    (123 /) needs to [OK!] be cleane...
dtype: object

Remove all digits:

>>> s = hero.remove_digits(s)
>>> s
0    This sèntencé    (  /) needs to [OK!] be cleaned!
dtype: object

Remove digits replaces only blocks of digits. The digits in the string "hello123" will not be removed. If we want to remove all digits, you need to set only_blocks to false.

Remove all types of brackets and their content.

>>> s = hero.remove_brackets(s)
>>> s 
0    This sèntencé    needs to  be cleaned!
dtype: object

Remove diacritics.

>>> s = hero.remove_diacritics(s)
>>> s 
0    This sentence    needs to  be cleaned!
dtype: object

Remove punctuation.

>>> s = hero.remove_punctuation(s)
>>> s 
0    This sentence    needs to  be cleaned
dtype: object

Remove extra white-spaces.

>>> s = hero.remove_whitespace(s)
>>> s 
0    This sentence needs to be cleaned
dtype: object

Sometimes we also want to get rid of stop-words.

>>> s = hero.remove_stopwords(s)
>>> s
0    This sentence needs cleaned
dtype: object

API

Texthero is composed of four modules: preprocessing.py, nlp.py, representation.py and visualization.py.

1. Preprocessing

Scope: prepare text data for further analysis.

Full documentation: preprocessing

2. NLP

Scope: provide classic natural language processing tools such as named_entity and noun_phrases.

Full documentation: nlp

2. Representation

Scope: map text data into vectors and do dimensionality reduction.

Supported representation algorithms:

  1. Term frequency (count)
  2. Term frequency-inverse document frequency (tfidf)

Supported clustering algorithms:

  1. K-means (kmeans)
  2. Density-Based Spatial Clustering of Applications with Noise (dbscan)
  3. Meanshift (meanshift)

Supported dimensionality reduction algorithms:

  1. Principal component analysis (pca)
  2. t-distributed stochastic neighbor embedding (tsne)
  3. Non-negative matrix factorization (nmf)

Full documentation: representation

3. Visualization

Scope: summarize the main facts regarding the text data and visualize it. This module is opinionable. It's handy for anyone that needs a quick solution to visualize on screen the text data, for instance during a text exploratory data analysis (EDA).

Supported functions:

  • Text scatterplot (scatterplot)
  • Most common words (top_words)

Full documentation: visualization

FAQ

Why Texthero

Sometimes we just want things done, right? Texthero helps with that. It helps make things easier and give the developer more time to focus on his custom requirements. We believe that cleaning text should just take a minute. Same for finding the most important part of a text and the same for representing it.

In a very pragmatic way, texthero has just one goal: make the developer spare time. Working with text data can be a pain and in most cases, a default pipeline can be quite good to start. There is always time to come back and improve previous work.

Contributions

"Texthero has been developed by a member of the NLP community for the whole NLP-community"

Texthero is for all of us NLP-developers and it can continue to exist with the precious contribution of the community.

Your level of expertise of python and NLP does not matter, anyone can help and anyone is more than welcome to contribute!

Are you an NLP expert?

  • open an issue and tell us what you like and dislike of Texthero and what we can do better!

Are you good at creating websites?

The website will be soon moved from Docusaurus to Sphinx: read the open issue there. Good news: the website will look like now :) Average news: we need to do some web-development to adapt this Sphinx template to our needs. Can you help us?

Are you good at writing?

Probably this is the most important piece missing now on Texthero: more tutorials and more "Getting Started" guide.

If you are good at writing you can help us! Why don't you start by Adding a FAQ page to the website or explain how to create a custom pipeline? Need help? We are there for you.

Are you good in python?

There are a lot of open issues for techie guys. Which one do you choose?

If you have just other questions or inquiry drop me a line at jonathanbesomi__AT__gmail.com

Contributors (in chronological order)

License

The MIT License (MIT)

Copyright (c) 2020 Texthero

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments
  • Change representation_series to DataFrame

    Change representation_series to DataFrame

    • all functions, which previously dealt with representation series now handle only the dataframe instead. 🚀

    • rm all functions like flatten, as they are not needed anymore

    • adopted docstrings and tests

    -> further stuff to do:

    • add those examples into the tutorials, readme, getting started
    enhancement 
    opened by mk2510 20
  • Can we avoid having a cell with a list?

    Can we avoid having a cell with a list?

    As we know, it's really not recommended to store a list in a Pandas cell. TokenSeries and VectorSeries, two of the core ideas of (current) Texthero are actually using it, can this process be avoided?

    Need to discuss:

    • Alternatives using sub-columns (it's still MultiIndex). Understand how complex and flexible this solution is. 99% of the cases, the standard Pandas/Texthero user does not really know how to work with MultiIndex ...
    • Can we just use RepresentationSeries? Probably not as we cannot merge it into a DataFrame with a single index, other alternatives than data alignment with reindex (too complicated)?

    @mk2510 @henrifroese

    discussion 
    opened by jbesomi 18
  • Add Lemmatization

    Add Lemmatization

    Lemmatization can be thought of as a more advanced stemming that we already have in the preprocessing module. You can read about it e.g. here. Implementation should be done with spaCy.

    ToDo

    Implement a function hero.lemmatize(s: TokenSeries) (or mayber rather TextSeries?). Using spaCy this should be fairly straightforward. It should go into the NLP module and probably look very similar to the other spacy-based functions there.

    Just comment below if you want to work on this and/or have any questions. I think this is a good first issue for new contributors.

    enhancement good first issue 
    opened by henrifroese 15
  • RepresentationSeries: count, term_frequency and tfidf

    RepresentationSeries: count, term_frequency and tfidf

    • Implement full support for Representation Series in "Vectorization" functions of representation module
    • add appropriate tests
    • add function_check_is_valid_representation

    We already wrote & tested all the code for Representation Series in the whole module, but we want to split this up into separate PRs so it's easier to review etc. As soon as this is merged, we'll open the other PRs.

    Roadmap for Representation Series implementation:

    1. This PR
    2. Implement Representation Series in rest of representation module over 2-3 more PRs
    3. Write tutorial for Representation Series
    4. Incorporate Representation Series into README and getting-started
    5. Release to PyPI
    enhancement 
    opened by henrifroese 15
  • replace `tokenize_with_phrases` with `phrases` and added tests

    replace `tokenize_with_phrases` with `phrases` and added tests

    This PR will replace tokenize_with_phrases with phrases. I added unit tests as well for phrases.

    This is the result of running ./tests.sh:

    ..............................................................................................................................................................
    ----------------------------------------------------------------------
    Ran 158 tests in 9.798s
    
    OK
    

    This is the result of running ./format.sh:

    All done! ✨ 🍰 ✨
    6 files left unchanged.
    All done! ✨ 🍰 ✨
    6 files left unchanged.
    
    opened by cedricconol 12
  • Update documentation docstrings etc

    Update documentation docstrings etc

    So this is quite a big PR that will finish the first part of #85 . We went through all docstrings and added examples/tests, added other arguments, and fixed some stuff along the way. We also updated the README.md and the getting-started.md

    Besides the docstrings updates, some small code changes are:

    • more parameters for the representation functions
    • change to scatterplot to support 3d visualization and return figure correctly

    I just went through some other issues and think that additionally this fixes

    • parts of #100 and #98
    • all of #99

    After this, in line with #85 , a new version should be deployed / published.

    opened by henrifroese 11
  • Update docstring for hero.wordcloud

    Update docstring for hero.wordcloud

    After the discussion on #78

    We should add something like:

    "To reduce blur in the images, width and height should have the same size, i.e the image should be squared"

    documentation good first issue 
    opened by vidyap-xgboost 11
  • Fix NaNs (Closes #86)

    Fix NaNs (Closes #86)

    Implement dealing with np.nan, closes #86

    Every function in the library now handles NaNs correctly.

    Implemented through decorator @handle_nans in new file _helper.py.

    Tests added in test_nan.py

    As we went through the whole library anyways, argument "input" was renamed to "s" in some functions to be in line with the others.

    opened by henrifroese 10
  • Added the function to  POS tag

    Added the function to POS tag

    @richramalho

    Added the function to POS tag.

    I saw the suggestions in PR #57 and read the CONTRIBUTING.md file.

    Any suggestions please tell me. Thank you!

    opened by ghost 9
  • Improve remove_diacritics function. Fixes #71

    Improve remove_diacritics function. Fixes #71

    The remove_diacritics function produced transliterated output for e.g. the Urdu alphabet.

    Through the unicodedata package, diacritics are now safely filtered out.

    opened by henrifroese 9
  • HeroTypes in Representation; DataFrame in _types

    HeroTypes in Representation; DataFrame in _types

    • switch DocumentTermDF in for RepresentationSeries in _types.py
    • add functionality for decorator @InputSeries to handle several allowed input types
    • Add typing decorator/hints to representation.py
    • add tests for DocumentTermDF type in test_types.py

    NOTE: only so many commits/lines as this builds on #156

    enhancement 
    opened by henrifroese 8
  • Is there any function to find how the weights are calculated for each word to represent a sentence?

    Is there any function to find how the weights are calculated for each word to represent a sentence?

    Is there any function or way to get the weights each word is given while calculating each component.

    I would want to see something like this? This will be really helpful as it will help me with interpretability in getting to know what weight was given to each word. image Source : https://www.displayr.com/principal-component-analysis-of-text-data/

    opened by cassin-edwin 0
  • installation error: Could not build wheels for spacy, which is required to install pyproject.toml-based projects

    installation error: Could not build wheels for spacy, which is required to install pyproject.toml-based projects

    Hi, I ran into an error when I tried to install Texthero. I already all packages needed such as spacy, gensim, etc. But when installation processed to building wheel for gensim, error showed up:

    Failed to build gensim spacy ERROR: Could not build wheels for spacy, which is required to install pyproject.toml-based projects

    I'm wondering if you can help point out in which direction I should be looking at to fix this. Is it pip or the spacy/ gensim is not pyproject.toml-based?

    Thanks.

    opened by Wes-Wwang 1
  • Import error

    Import error

    KeyError: "[E002] Can't find factory for 'tok2vec'. This usually happens when spaCy calls nlp.create_pipe with a component name that's not built in - for example, when constructing the pipeline from a model's meta.json. If you're using a custom component, you can write to Language.factories['tok2vec'] or remove it from the model meta and add it via nlp.add_pipe instead.

    Tried in my virtual environment and kaggle, it doesn't working.

    image

    opened by RAravindDS 2
  • Deprecated arguments on kmeans function call

    Deprecated arguments on kmeans function call

    When I tried to use kmeans I noticed that a couple of deprecated arguments were used to make the function call: precompute_distances and n_jobs. After I removed them it worked fine. Tried both on version 1.1.0 and 1.0.9. I would make a PR about it but the code on the main branch looks different from the one installed with pip install.

    opened by svthiago 5
  • `remove_punctuation()` is not removing

    `remove_punctuation()` is not removing "\"

    >>> import texthero as hero
    >>> import pandas as pd
    >>> import string
    >>>
    >>> s = pd.Series(rf"{string.punctuation}")
    >>> hero.remove_punctuation(s)
    0     \ 
    dtype: object
    
    opened by batmanscode 0
Releases(1.1.0)
Owner
Jonathan Besomi
NLP and text mining.
Jonathan Besomi
All the code I wrote for Overwatch-related projects that I still own the rights to.

overwatch_shit.zip This is (eventually) going to contain all the software I wrote during my five-year imprisonment stay playing Overwatch. I'll be add

zkxjzmswkwl 2 Dec 31, 2021
Galois is an auto code completer for code editors (or any text editor) based on OpenAI GPT-2.

Galois is an auto code completer for code editors (or any text editor) based on OpenAI GPT-2. It is trained (finetuned) on a curated list of approximately 45K Python (~470MB) files gathered from the

Galois Autocompleter 91 Sep 23, 2022
Trains an OpenNMT PyTorch model and SentencePiece tokenizer.

Trains an OpenNMT PyTorch model and SentencePiece tokenizer. Designed for use with Argos Translate and LibreTranslate.

Argos Open Tech 61 Dec 13, 2022
Yet Another Compiler Visualizer

yacv: Yet Another Compiler Visualizer yacv is a tool for visualizing various aspects of typical LL(1) and LR parsers. Check out demo on YouTube to see

Ashutosh Sathe 129 Dec 17, 2022
A PyTorch implementation of paper "Learning Shared Semantic Space for Speech-to-Text Translation", ACL (Findings) 2021

Chimera: Learning Shared Semantic Space for Speech-to-Text Translation This is a Pytorch implementation for the "Chimera" paper Learning Shared Semant

Chi Han 43 Dec 28, 2022
TTS is a library for advanced Text-to-Speech generation.

TTS is a library for advanced Text-to-Speech generation. It's built on the latest research, was designed to achieve the best trade-off among ease-of-training, speed and quality. TTS comes with pretra

Mozilla 6.5k Jan 08, 2023
A calibre plugin that generates Word Wise and X-Ray files then sends them to Kindle. Supports KFX, AZW3 and MOBI eBooks. X-Ray supports 18 languages.

WordDumb A calibre plugin that generates Word Wise and X-Ray files then sends them to Kindle. Supports KFX, AZW3 and MOBI eBooks. Languages X-Ray supp

172 Dec 29, 2022
🍊 PAUSE (Positive and Annealed Unlabeled Sentence Embedding), accepted by EMNLP'2021 🌴

PAUSE: Positive and Annealed Unlabeled Sentence Embedding Sentence embedding refers to a set of effective and versatile techniques for converting raw

EQT 21 Dec 15, 2022
SAINT PyTorch implementation

SAINT-pytorch A Simple pyTorch implementation of "Towards an Appropriate Query, Key, and Value Computation for Knowledge Tracing" based on https://arx

Arshad Shaikh 63 Dec 25, 2022
Count the frequency of letters or words in a text file and show a graph.

Word Counter By EBUS Coding Club Count the frequency of letters or words in a text file and show a graph. Requirements Python 3.9 or higher matplotlib

EBUS Coding Club 0 Apr 09, 2022
Understanding the Difficulty of Training Transformers

Admin Understanding the Difficulty of Training Transformers Guided by our analyses, we propose Adaptive Model Initialization (Admin), which successful

Liyuan Liu 300 Dec 29, 2022
🤗 Transformers: State-of-the-art Natural Language Processing for Pytorch, TensorFlow, and JAX.

English | 简体中文 | 繁體中文 State-of-the-art Natural Language Processing for Jax, PyTorch and TensorFlow 🤗 Transformers provides thousands of pretrained mo

Hugging Face 77.2k Jan 03, 2023
🎐 a python library for doing approximate and phonetic matching of strings.

jellyfish Jellyfish is a python library for doing approximate and phonetic matching of strings. Written by James Turk James Turk 1.8k Dec 21, 2022

Python bindings to the dutch NLP tool Frog (pos tagger, lemmatiser, NER tagger, morphological analysis, shallow parser, dependency parser)

Frog for Python This is a Python binding to the Natural Language Processing suite Frog. Frog is intended for Dutch and performs part-of-speech tagging

Maarten van Gompel 46 Dec 14, 2022
Winner system (DAMO-NLP) of SemEval 2022 MultiCoNER shared task over 10 out of 13 tracks.

KB-NER: a Knowledge-based System for Multilingual Complex Named Entity Recognition The code is for the winner system (DAMO-NLP) of SemEval 2022 MultiC

116 Dec 27, 2022
VoiceFixer VoiceFixer is a framework for general speech restoration.

VoiceFixer VoiceFixer is a framework for general speech restoration. We aim at the restoration of severly degraded speech and historical speech. Paper

Leo 174 Jan 06, 2023
An Open-Source Package for Neural Relation Extraction (NRE)

OpenNRE We have a DEMO website (http://opennre.thunlp.ai/). Try it out! OpenNRE is an open-source and extensible toolkit that provides a unified frame

THUNLP 3.9k Jan 03, 2023
Unet-TTS: Improving Unseen Speaker and Style Transfer in One-shot Voice Cloning

Unet-TTS: Improving Unseen Speaker and Style Transfer in One-shot Voice Cloning English | 中文 ❗ Now we provide inferencing code and pre-training models

164 Jan 02, 2023
State of the art faster Natural Language Processing in Tensorflow 2.0 .

tf-transformers: faster and easier state-of-the-art NLP in TensorFlow 2.0 ****************************************************************************

74 Dec 05, 2022
Code release for "COTR: Correspondence Transformer for Matching Across Images"

COTR: Correspondence Transformer for Matching Across Images This repository contains the inference code for COTR. We plan to release the training code

UBC Computer Vision Group 358 Dec 24, 2022