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
Machine learning classifiers to predict American Sign Language .

ASL-Classifiers American Sign Language (ASL) is a natural language that serves as the predominant sign language of Deaf communities in the United Stat

Tarek idrees 0 Feb 08, 2022
运小筹公众号是致力于分享运筹优化(LP、MIP、NLP、随机规划、鲁棒优化)、凸优化、强化学习等研究领域的内容以及涉及到的算法的代码实现。

OlittleRer 运小筹公众号是致力于分享运筹优化(LP、MIP、NLP、随机规划、鲁棒优化)、凸优化、强化学习等研究领域的内容以及涉及到的算法的代码实现。编程语言和工具包括Java、Python、Matlab、CPLEX、Gurobi、SCIP 等。 关注我们: 运筹小公众号 有问题可以直接在

运小筹 151 Dec 30, 2022
The model is designed to train a single and large neural network in order to predict correct translation by reading the given sentence.

Neural Machine Translation communication system The model is basically direct to convert one source language to another targeted language using encode

Nishant Banjade 7 Sep 22, 2022
Twitter-NLP-Analysis - Twitter Natural Language Processing Analysis

Twitter-NLP-Analysis Business Problem I got last @turk_politika 3000 tweets with

Çağrı Karadeniz 7 Mar 12, 2022
A python project made to generate code using either OpenAI's codex or GPT-J (Although not as good as codex)

CodeJ A python project made to generate code using either OpenAI's codex or GPT-J (Although not as good as codex) Install requirements pip install -r

TheProtagonist 1 Dec 06, 2021
Dust model dichotomous performance analysis

Dust-model-dichotomous-performance-analysis Using a collated dataset of 90,000 dust point source observations from 9 drylands studies from around the

1 Dec 17, 2021
AudioCLIP Extending CLIP to Image, Text and Audio

AudioCLIP Extending CLIP to Image, Text and Audio This repository contains implementation of the models described in the paper arXiv:2106.13043. This

458 Jan 02, 2023
🤗 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
BiNE: Bipartite Network Embedding

BiNE: Bipartite Network Embedding This repository contains the demo code of the paper: BiNE: Bipartite Network Embedding. Ming Gao, Leihui Chen, Xiang

leihuichen 214 Nov 24, 2022
A look-ahead multi-entity Transformer for modeling coordinated agents.

baller2vec++ This is the repository for the paper: Michael A. Alcorn and Anh Nguyen. baller2vec++: A Look-Ahead Multi-Entity Transformer For Modeling

Michael A. Alcorn 30 Dec 16, 2022
official ( API ) for the zAmericanEnglish app in [ Google play ] and [ App store ]

official ( API ) for the zAmericanEnglish app in [ Google play ] and [ App store ]

Plugin 3 Jan 12, 2022
Code for using and evaluating SpanBERT.

SpanBERT This repository contains code and models for the paper: SpanBERT: Improving Pre-training by Representing and Predicting Spans. If you prefer

Meta Research 798 Dec 30, 2022
Machine Psychology: Python Generated Art

Machine Psychology: Python Generated Art A limited collection of 64 algorithmically generated artwork. Each unique piece is then given a title by the

Pixegami Team 67 Dec 13, 2022
⚡ boost inference speed of T5 models by 5x & reduce the model size by 3x using fastT5.

Reduce T5 model size by 3X and increase the inference speed up to 5X. Install Usage Details Functionalities Benchmarks Onnx model Quantized onnx model

Kiran R 399 Jan 05, 2023
(ACL-IJCNLP 2021) Convolutions and Self-Attention: Re-interpreting Relative Positions in Pre-trained Language Models.

BERT Convolutions Code for the paper Convolutions and Self-Attention: Re-interpreting Relative Positions in Pre-trained Language Models. Contains expe

mlpc-ucsd 21 Jul 18, 2022
Transformer training code for sequential tasks

Sequential Transformer This is a code for training Transformers on sequential tasks such as language modeling. Unlike the original Transformer archite

Meta Research 578 Dec 13, 2022
Blue Brain text mining toolbox for semantic search and structured information extraction

Blue Brain Search Source Code DOI Data & Models DOI Documentation Latest Release Python Versions License Build Status Static Typing Code Style Securit

The Blue Brain Project 29 Dec 01, 2022
Composed Image Retrieval using Pretrained LANguage Transformers (CIRPLANT)

CIRPLANT This repository contains the code and pre-trained models for Composed Image Retrieval using Pretrained LANguage Transformers (CIRPLANT) For d

Zheyuan (David) Liu 29 Nov 17, 2022
A high-level Python library for Quantum Natural Language Processing

lambeq About lambeq is a toolkit for quantum natural language processing (QNLP). Documentation: https://cqcl.github.io/lambeq/ Getting started Prerequ

Cambridge Quantum 315 Jan 01, 2023