language_tool_python
language_tool_python copied to clipboard
Add suggestion choice method
Sometimes LanguageTool gives several suggestions. In the case below, for this sentence in which I made a typo in the word ‘book’, I end up with a ton of suggestions. The correct suggestion is the third one.
import language_tool_python
def patch_text(text):
with language_tool_python.LanguageTool('en-US') as tool:
errors = tool.check(text)
patched_text = language_tool_python.utils.correct(text, errors)
return patched_text
if __name__ == '__main__':
text = """
There is a bok on the table.
"""
print(patch_text(text))
[Match({'ruleId': 'MORFOLOGIK_RULE_EN_US', 'message': 'Possible spelling mistake found.', 'replacements': ['BOK', 'OK', 'book', 'box', ...], 'offsetInContext': 12, 'context': ' There is a bok on the table. ', 'offset': 12, 'errorLength': 3, 'category': 'TYPOS', 'ruleIssueType': 'misspelling', 'sentence': 'There is a bok on the table.'})]
By default, correct applies the first suggestion on the list. So I end up with this sentence:
There is a BOK on the table.
With my update, you can now choose a suggestion for each Match, and then change the Match list to correct func:
import language_tool_python
def patch_text(text):
with language_tool_python.LanguageTool('en-US') as tool:
matches = tool.check(text)
for match in matches:
if not match.replacements:
continue
print(match)
index = input("Enter the index of the suggestion you want to apply: ")
match.select_replacement(int(index)) # new method
patched_text = language_tool_python.utils.correct(text, matches)
return patched_text
if __name__ == '__main__':
text = """
There is a bok on the table.
"""
print(patch_text(text))
So I can end up with the sentence I want:
There is a book on the table.
This is a simple example, but in my case, when I'm doing interactive correction of large texts with this library, I end up having to modify the Matches myself, rather than using a method implemented in the library.