Lo-Fi Python

Jan 30, 2022

Fix Spelling and Grammar with language_tool_python and textblob

Below are two practical Python libraries for text processing. This function uses textblob's spelling correction along with language_tool_python, which applies grammatical corrections via the Language Tool API. I added these text processing transformations into my concept text generation app. These are free, public APIs up to around 20 requests per second. You can send both text and receive back an improved version of your text, ideally altering and improving your writing.

I found 2 errors when I piped the text of this post into the below code: the proper noun "textblob" corrected to "text blow's" and the word "app" corrected to "pp". Be sure to proof your results. Regardless, I like having these two Python tools in my bag!

Install

textblob

language_tool_python

help with pip

pip install language-tool-python
pip install -U textblob
python -m textblob.download_corpora
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import language_tool_python
from textblob import TextBlob

def fix_spelling_and_grammar(text):
    """Returns str: text transformed by language tool and text blob
    1) Apply language tool API correction
    Language Tool Public API: https://dev.languagetool.org/public-http-api
    https://languagetool.org/http-api/swagger-ui/#!/default/post_check
    python library: https://pypi.org/project/language-tool-python/

    2) Apply textblob's spell check to the text"""
    try:
        # use the public API, language English
        tool = language_tool_python.LanguageToolPublicAPI('en-US')
        text =  tool.correct(text)
        b = TextBlob(text)
        return str(b.correct())
    except:
        return text

text = "Language is incredble. Fascinatng how hoomans have so many."
transformed_text = fix_spelling_and_grammar(text)
print(transformed_text)
# Result: Language is incredible. Fascinating how humans have so many.