Skip to content

Commit fd028ce

Browse files
committed
Add correct method and function.
1 parent 2ed269b commit fd028ce

1 file changed

Lines changed: 23 additions & 1 deletion

File tree

‎language_tool/__init__.py‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737

3838

3939
__all__ = ["LanguageTool", "Error",
40-
"get_languages", "get_version", "get_version_info",
40+
"get_languages", "correct", "get_version", "get_version_info",
4141
"get_language_tool_dir", "set_language_tool_dir"]
4242

4343
FAILSAFE_LANGUAGE = "en"
@@ -181,6 +181,11 @@ def check(self, text: str, srctext=None) -> [Match]:
181181
root = self._get_root(self.url, data)
182182
return [Match(e.attrib, self.language) for e in root]
183183

184+
def correct(self, text: str, srctext=None) -> str:
185+
"""Automatically apply suggestions to the text.
186+
"""
187+
return correct(text, self.check(text, srctext))
188+
184189
@classmethod
185190
def _get_languages(cls):
186191
if not cls._server_is_alive():
@@ -323,6 +328,23 @@ def _normalize(tag):
323328
raise ValueError("unsupported language: {!r}".format(tag))
324329

325330

331+
def correct(text: str, matches: [Match]) -> str:
332+
"""Automatically apply suggestions to the text.
333+
"""
334+
ltext = list(text)
335+
matches = [match for match in matches if match.replacements]
336+
errors = [ltext[match.frompos:match.topos] for match in matches]
337+
offset = 0
338+
for n, match in enumerate(matches):
339+
frompos, topos = match.frompos + offset, match.topos + offset
340+
if ltext[frompos:topos] != errors[n]:
341+
continue
342+
repl = match.replacements[0]
343+
ltext[frompos:topos] = list(repl)
344+
offset += len(repl) - len(errors[n])
345+
return "".join(ltext)
346+
347+
326348
def get_version():
327349
"""Get LanguageTool version as a string.
328350
"""

0 commit comments

Comments
 (0)