|
37 | 37 | from __future__ import annotations |
38 | 38 |
|
39 | 39 | import contextlib |
| 40 | +import difflib |
40 | 41 | import functools |
41 | 42 | import importlib |
42 | 43 | import inspect |
@@ -114,6 +115,47 @@ def wrapper(*args, **kwargs): |
114 | 115 | return wrapper |
115 | 116 |
|
116 | 117 |
|
| 118 | +def did_you_mean( |
| 119 | + word: Hashable, possibilities: Iterable[Hashable], *, n: int = 10 |
| 120 | +) -> str: |
| 121 | + """ |
| 122 | + Suggest a few correct words based on a list of possibilites |
| 123 | +
|
| 124 | + Parameters |
| 125 | + ---------- |
| 126 | + word : Hashable |
| 127 | + Word to compare to a list of possibilites. |
| 128 | + possibilities : Iterable of Hashable |
| 129 | + The iterable of Hashable that contains the correct values. |
| 130 | + n : int, default: 10 |
| 131 | + Maximum number of suggestions to show. |
| 132 | +
|
| 133 | + Examples |
| 134 | + -------- |
| 135 | + >>> did_you_mean("bluch", ("blech", "gray_r", 1, None, (2, 56))) |
| 136 | + "Did you mean one of ('blech',)?" |
| 137 | + >>> did_you_mean("none", ("blech", "gray_r", 1, None, (2, 56))) |
| 138 | + 'Did you mean one of (None,)?' |
| 139 | +
|
| 140 | + See also |
| 141 | + -------- |
| 142 | + https://en.wikipedia.org/wiki/String_metric |
| 143 | + """ |
| 144 | + # Convert all values to string, get_close_matches doesn't handle all hashables: |
| 145 | + possibilites_str: dict[str, Hashable] = {str(k): k for k in possibilities} |
| 146 | + |
| 147 | + msg = "" |
| 148 | + if len( |
| 149 | + best_str := difflib.get_close_matches( |
| 150 | + str(word), list(possibilites_str.keys()), n=n |
| 151 | + ) |
| 152 | + ): |
| 153 | + best = tuple(possibilites_str[k] for k in best_str) |
| 154 | + msg = f"Did you mean one of {best}?" |
| 155 | + |
| 156 | + return msg |
| 157 | + |
| 158 | + |
117 | 159 | def get_valid_numpy_dtype(array: np.ndarray | pd.Index) -> np.dtype: |
118 | 160 | """Return a numpy compatible dtype from either |
119 | 161 | a numpy array or a pandas.Index. |
|
0 commit comments