Debian Codegraph @

brian2/utils/stringtools.py

raw
1 """
2 A collection of tools for string formatting tasks.
3 """
4
5 import re
6 import string
7
8 __all__ = [
9 "indent",
10 "deindent",
11 "word_substitute",
12 "replace",
13 "get_identifiers",
14 "strip_empty_lines",
15 "stripped_deindented_lines",
16 "strip_empty_leading_and_trailing_lines",
17 "code_representation",
18 "SpellChecker",
19 ]
20
21
22 def indent(text, numtabs=1, spacespertab=4, tab=None):
23 """
24 Indents a given multiline string.
25
26 By default, indentation is done using spaces rather than tab characters.
27 To use tab characters, specify the tab character explictly, e.g.::
28
29 indent(text, tab='\t')
30
31 Note that in this case ``spacespertab`` is ignored.
32
33 Examples
34 --------
35 >>> multiline = '''def f(x):
36 ... return x*x'''
37 >>> print(multiline)
38 def f(x):
39 return x*x
40 >>> print(indent(multiline))
41 def f(x):
42 return x*x
43 >>> print(indent(multiline, numtabs=2))
44 def f(x):
45 return x*x
46 >>> print(indent(multiline, spacespertab=2))
47 def f(x):
48 return x*x
49 >>> print(indent(multiline, tab='####'))
50 ####def f(x):
51 #### return x*x
52 """
53 if tab is None:
54 tab = " " * spacespertab
55 indent = tab * numtabs
56 indentedstring = indent + text.replace("\n", f"\n{indent}")
57 return indentedstring
58
59
60 def deindent(text, numtabs=None, spacespertab=4, docstring=False):
61 """
62 Returns a copy of the string with the common indentation removed.
63
64 Note that all tab characters are replaced with ``spacespertab`` spaces.
65
66 If the ``docstring`` flag is set, the first line is treated differently and
67 is assumed to be already correctly tabulated.
68
69 If the ``numtabs`` option is given, the amount of indentation to remove is
70 given explicitly and not the common indentation.
71
72 Examples
73 --------
74 Normal strings, e.g. function definitions:
75
76 >>> multiline = ''' def f(x):
77 ... return x**2'''
78 >>> print(multiline)
79 def f(x):
80 return x**2
81 >>> print(deindent(multiline))
82 def f(x):
83 return x**2
84 >>> print(deindent(multiline, docstring=True))
85 def f(x):
86 return x**2
87 >>> print(deindent(multiline, numtabs=1, spacespertab=2))
88 def f(x):
89 return x**2
90
91 Docstrings:
92
93 >>> docstring = '''First docstring line.
94 ... This line determines the indentation.'''
95 >>> print(docstring)
96 First docstring line.
97 This line determines the indentation.
98 >>> print(deindent(docstring, docstring=True))
99 First docstring line.
100 This line determines the indentation.
101 """
102 text = text.replace("\t", " " * spacespertab)
103 lines = text.split("\n")
104 # if it's a docstring, we search for the common tabulation starting from
105 # line 1, otherwise we use all lines
106 if docstring:
107 start = 1
108 else:
109 start = 0
110 if docstring and len(lines) < 2: # nothing to do
111 return text
112 # Find the minimum indentation level
113 if numtabs is not None:
114 indentlevel = numtabs * spacespertab
115 else:
116 lineseq = [
117 len(line) - len(line.lstrip())
118 for line in lines[start:]
119 if len(line.strip())
120 ]
121 if len(lineseq) == 0:
122 indentlevel = 0
123 else:
124 indentlevel = min(lineseq)
125 # remove the common indentation
126 lines[start:] = [line[indentlevel:] for line in lines[start:]]
127 return "\n".join(lines)
128
129
130 def word_substitute(expr, substitutions):
131 """
132 Applies a dict of word substitutions.
133
134 The dict ``substitutions`` consists of pairs ``(word, rep)`` where each
135 word ``word`` appearing in ``expr`` is replaced by ``rep``. Here a 'word'
136 means anything matching the regexp ``\\bword\\b``.
137
138 Examples
139 --------
140
141 >>> expr = 'a*_b+c5+8+f(A)'
142 >>> print(word_substitute(expr, {'a':'banana', 'f':'func'}))
143 banana*_b+c5+8+func(A)
144 """
145 for var, replace_var in substitutions.items():
146 expr = re.sub(f"\\b{var}\\b", str(replace_var), expr)
147 return expr
148
149
150 def replace(s, substitutions):
151 """
152 Applies a dictionary of substitutions. Simpler than `word_substitute`, it
153 does not attempt to only replace words
154 """
155 for before, after in substitutions.items():
156 s = s.replace(before, after)
157 return s
158
159
160 KEYWORDS = {"and", "or", "not", "True", "False"}
161
162
163 def get_identifiers(expr, include_numbers=False):
164 """
165 Return all the identifiers in a given string ``expr``, that is everything
166 that matches a programming language variable like expression, which is
167 here implemented as the regexp ``\\b[A-Za-z_][A-Za-z0-9_]*\\b``.
168
169 Parameters
170 ----------
171 expr : str
172 The string to analyze
173 include_numbers : bool, optional
174 Whether to include number literals in the output. Defaults to ``False``.
175
176 Returns
177 -------
178 identifiers : set
179 A set of all the identifiers (and, optionally, numbers) in `expr`.
180
181 Examples
182 --------
183 >>> expr = '3-a*_b+c5+8+f(A - .3e-10, tau_2)*17'
184 >>> ids = get_identifiers(expr)
185 >>> print(sorted(list(ids)))
186 ['A', '_b', 'a', 'c5', 'f', 'tau_2']
187 >>> ids = get_identifiers(expr, include_numbers=True)
188 >>> print(sorted(list(ids)))
189 ['.3e-10', '17', '3', '8', 'A', '_b', 'a', 'c5', 'f', 'tau_2']
190 """
191 identifiers = set(re.findall(r"\b[A-Za-z_][A-Za-z0-9_]*\b", expr))
192 if include_numbers:
193 # only the number, not a + or -
194 numbers = set(
195 re.findall(
196 r"(?<=[^A-Za-z_])[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?|^[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?",
197 expr,
198 )
199 )
200 else:
201 numbers = set()
202 return (identifiers - KEYWORDS) | numbers
203
204
205 def strip_empty_lines(s):
206 """
207 Removes all empty lines from the multi-line string `s`.
208
209 Examples
210 --------
211
212 >>> multiline = '''A string with
213 ...
214 ... an empty line.'''
215 >>> print(strip_empty_lines(multiline))
216 A string with
217 an empty line.
218 """
219 return "\n".join(line for line in s.split("\n") if line.strip())
220
221
222 def strip_empty_leading_and_trailing_lines(s):
223 """
224 Removes all empty leading and trailing lines in the multi-line string `s`.
225 """
226 lines = s.split("\n")
227 while lines and not lines[0].strip():
228 del lines[0]
229 while lines and not lines[-1].strip():
230 del lines[-1]
231 return "\n".join(lines)
232
233
234 def stripped_deindented_lines(code):
235 """
236 Returns a list of the lines in a multi-line string, deindented.
237 """
238 code = deindent(code)
239 code = strip_empty_lines(code)
240 lines = code.split("\n")
241 return lines
242
243
244 def code_representation(code):
245 """
246 Returns a string representation for several different formats of code
247
248 Formats covered include:
249 - A single string
250 - A list of statements/strings
251 - A dict of strings
252 - A dict of lists of statements/strings
253 """
254 if not isinstance(code, (str, list, tuple, dict)):
255 code = str(code)
256 if isinstance(code, str):
257 return strip_empty_leading_and_trailing_lines(code)
258 if not isinstance(code, dict):
259 code = {None: code}
260 else:
261 code = code.copy()
262 for k, v in code.items():
263 if isinstance(v, (list, tuple)):
264 v = "\n".join([str(line) for line in v])
265 code[k] = v
266 if len(code) == 1 and list(code.keys())[0] is None:
267 return strip_empty_leading_and_trailing_lines(list(code.values())[0])
268 output = []
269 for k, v in code.items():
270 msg = f"Key {k}:\n"
271 msg += indent(str(v))
272 output.append(msg)
273 return strip_empty_leading_and_trailing_lines("\n".join(output))
274
275
276 # The below is adapted from Peter Norvig's spelling corrector
277 # http://norvig.com/spell.py (MIT licensed)
278 class SpellChecker:
279 """
280 A simple spell checker that will be used to suggest the correct name if the
281 user made a typo (e.g. for state variable names).
282
283 Parameters
284 ----------
285 words : iterable of str
286 The known words
287 alphabet : iterable of str, optional
288 The allowed characters. Defaults to the characters allowed for
289 identifiers, i.e. ascii characters, digits and the underscore.
290 """
291
292 def __init__(self, words, alphabet=f"{string.ascii_lowercase + string.digits}_"):
293 self.words = words
294 self.alphabet = alphabet
295
296 def edits1(self, word):
297 s = [(word[:i], word[i:]) for i in range(len(word) + 1)]
298 deletes = [a + b[1:] for a, b in s if b]
299 transposes = [a + b[1] + b[0] + b[2:] for a, b in s if len(b) > 1]
300 replaces = [a + c + b[1:] for a, b in s for c in self.alphabet if b]
301 inserts = [a + c + b for a, b in s for c in self.alphabet]
302 return set(deletes + transposes + replaces + inserts)
303
304 def known_edits2(self, word):
305 return {
306 e2 for e1 in self.edits1(word) for e2 in self.edits1(e1) if e2 in self.words
307 }
308
309 def known(self, words):
310 return {w for w in words if w in self.words}
311
312 def suggest(self, word):
313 return self.known(self.edits1(word)) or self.known_edits2(word) or set()