Skip to content

Commit 78b6240

Browse files
authored
Merge pull request #95 from mdevolde/add-suggestion-choice-method
Add suggestion choice method
2 parents 455c5bd + 9a0d771 commit 78b6240

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

README.md

+17
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,23 @@ If you want to decide which `Match` objects to apply to your text, use `tool.che
5454
'Department of medicine Colombia University closed on August 1 Melinda Sam'
5555
```
5656

57+
### Apply a specific suggestion of a match with `Match.select_replacement` and `utils.correct`
58+
59+
If you want to apply a particular suggestion from a `Match`, use `Match.select_replacement` (to select a replacement with its index) in conjunction with `language_tool_python.utils.correct` (to apply selected replacements from the `Match` list to the text). Here is an example of generating, selecting replacements, and applying the list of matches. In this case, the third replacement (book) is selected.
60+
61+
```python
62+
>>> import language_tool_python
63+
>>> s = "There is a bok on the table."
64+
>>> tool = language_tool_python.LanguageTool('en-US')
65+
>>> matches = tool.check(s)
66+
>>> matches
67+
[Match({'ruleId': 'MORFOLOGIK_RULE_EN_US', 'message': 'Possible spelling mistake found.', 'replacements': ['BOK', 'OK', 'book', 'box'], 'offsetInContext': 11, 'context': 'There is a bok on the table.', 'offset': 11, 'errorLength': 3, 'category': 'TYPOS', 'ruleIssueType': 'misspelling', 'sentence': 'There is a bok on the table.'})]
68+
>>> matches[0].select_replacement(2)
69+
>>> patched_text = language_tool_python.utils.correct(s, matches)
70+
>>> patched_text
71+
'There is a book on the table.'
72+
```
73+
5774
## Example usage
5875

5976
From the interpreter:

language_tool_python/match.py

+9
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,15 @@ def matchedText(self):
9696
""" Returns the text that garnered the error (without its surrounding context).
9797
"""
9898
return self.context[self.offsetInContext:self.offsetInContext+self.errorLength]
99+
100+
def select_replacement(self, index: int) -> None:
101+
"""Choose one suggestion and delete the others. Usefull when you want to apply a specific suggestion.\n
102+
By default, the first suggestion is chosen."""
103+
if not self.replacements:
104+
raise ValueError('This Match has no suggestions')
105+
elif index < 0 or index >= len(self.replacements):
106+
raise ValueError('This Match\'s suggestions are numbered from 0 to {}'.format(len(self.replacements) - 1))
107+
self.replacements = [self.replacements[index]]
99108

100109
def __eq__(self, other):
101110
return list(self) == list(other)

0 commit comments

Comments
 (0)