|
37 | 37 |
|
38 | 38 |
|
39 | 39 | __all__ = ["LanguageTool", "Error", |
40 | | - "get_languages", "get_version", "get_version_info", |
| 40 | + "get_languages", "correct", "get_version", "get_version_info", |
41 | 41 | "get_language_tool_dir", "set_language_tool_dir"] |
42 | 42 |
|
43 | 43 | FAILSAFE_LANGUAGE = "en" |
@@ -181,6 +181,11 @@ def check(self, text: str, srctext=None) -> [Match]: |
181 | 181 | root = self._get_root(self.url, data) |
182 | 182 | return [Match(e.attrib, self.language) for e in root] |
183 | 183 |
|
| 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 | + |
184 | 189 | @classmethod |
185 | 190 | def _get_languages(cls): |
186 | 191 | if not cls._server_is_alive(): |
@@ -323,6 +328,23 @@ def _normalize(tag): |
323 | 328 | raise ValueError("unsupported language: {!r}".format(tag)) |
324 | 329 |
|
325 | 330 |
|
| 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 | + |
326 | 348 | def get_version(): |
327 | 349 | """Get LanguageTool version as a string. |
328 | 350 | """ |
|
0 commit comments