Execute a Markov algorithm: Difference between revisions
→{{header|Python}}: Simplified control flow in 'replace'.
m (→{{header|J}}) |
Underscore (talk | contribs) (→{{header|Python}}: Simplified control flow in 'replace'.) |
||
Line 283:
The example uses a regexp to parse the syntax of the grammar. This regexp is multi-line, verbose and uses named groups to aid in understanding the regexp and to allow more meaningful group names to be used when extracting the replacement data from the grammars in function <code>extractreplacements</code>.
<lang python>import re
syntaxre = r"""(?mx)
Line 339 ⟶ 338:
def replace(text, replacements):
▲ for (pat, repl, isterm) in replacements:
if pat in text:
text = text.replace(pat, repl, 1)
return text▼
break
else:
▲ return text
if __name__ == '__main__':
Line 357 ⟶ 355:
# Stretch goal
assert replace(text2, extractreplacements(grammar3)) \
== 'I bought a bag of apples with my money from T shop.'</lang>
=={{header|Ruby}}==
|