Code Fragment: Highlighting Typos

Another of those occasional examples of why I think it can be handy folk know how to code… a simple code fragment to style the output of a spell checker:

# Spell checking and grammar checking using:
#
# - https://github.com/jxmorris12/language_tool_python/
# - https://languagetool.org/

# %pip install --upgrade language_tool_python

import language_tool_python
tool = language_tool_python.LanguageTool('en-US')

text = 'This sentence is fine. A sentence with a error in the Hitchhiker’s Guide tot he Galaxy'
matches = tool.check(text)
matches


def styler(error):
    html = error.context
    from_ = error.offsetInContext
    to_ = from_ + error.errorLength
    txt = html[from_:to_]
    html =  html[:from_] + '<span style="color:red">' + txt +"</span>"+ html[to_:]
    print(f"**{html}")
    return html


from IPython.display import HTML
display(HTML(styler(matches[0])))

display(HTML(styler(matches[1])))

I did think I’d find a simple Jupyter extension to add languagetool support (using something like language_tool_python) to check notebook markdown cells, but from a quick search, I couldn’t find one offhand…?

Author: Tony Hirst

I'm a Senior Lecturer at The Open University, with an interest in #opendata policy and practice, as well as general web tinkering...

%d bloggers like this: