Jump to content

Execute a Markov algorithm: Difference between revisions

→‎{{header|Python}}: Add stretch goal solution
mNo edit summary
(→‎{{header|Python}}: Add stretch goal solution)
Line 101:
The example uses a regexp to parse the syntax of the grammar. This regexp is multi-line and 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
import re
 
syntaxre = r"""(?mx)
Line 126 ⟶ 127:
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
'''
 
grammar3 = '''\
# BNF Syntax testing rules
A -> apple
WWWW -> with
Bgage -> ->.*
B -> bag
->.* -> money
W -> WW
S -> .shop
T -> the
Line 133 ⟶ 148:
 
text1 = "I bought a B of As from T S."
 
text2 = "I bought a B of As W my Bgage from T S."
 
def extractreplacements(grammar):
Line 155 ⟶ 172:
== 'I bought a bag of apples from my brother.'
assert replace(text1, extractreplacements(grammar2)) \
== 'I bought a bag of apples from T shop.'</lang>
# Stretch goal
assert replace(text2, extractreplacements(grammar3)) \
== 'I bought a bag of apples with my money from T shop.'
</lang>
 
=={{header|Ruby}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.