Execute a Markov algorithm: Difference between revisions

Add Python
(→‎{{header|Tcl}}: Alternative, which is formally incorrect)
(Add Python)
Line 66:
I bought a bag of apples from my brother.</lang>
'''Discussion''': This solution implemented in 20 seconds and doesn't fully implement a Markov algorithm. More details on [[Talk:Markov Algorithm#J|the talk page]].
 
=={{header|Python}}==
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
 
syntaxre = r"""(?mx)
^(?:
(?: (?P<comment> \# .* ) ) |
(?: (?P<blank> \s* ) (?: \n | $ ) ) |
(?: (?P<rule> (?P<pat> .+? ) \s+ -> \s+ (?P<term> \.)? (?P<repl> .+) ) )
)$
"""
 
grammar1 = """\
# This rules file is extracted from Wikipedia:
# http://en.wikipedia.org/wiki/Markov_Algorithm
A -> apple
B -> bag
S -> shop
T -> the
the shop -> my brother
a never used -> .terminating rule
"""
 
grammar2 = '''\
# Slightly modified from the rules on Wikipedia
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
'''
 
text1 = "I bought a B of As from T S."
 
def extractreplacements(grammar):
return [ (matchobj.group('pat'), matchobj.group('repl'), bool(matchobj.group('term')))
for matchobj in re.finditer(syntaxre, grammar)
if matchobj.groupdict()['rule']]
 
def replace(text, replacements):
terminate = False
while not terminate:
for (pat, repl, isterm) in replacements:
if pat in text:
text = text.replace(pat, repl, 1)
terminate = isterm
break
else:
terminate = True
return text
 
if __name__ == '__main__':
assert replace(text1, extractreplacements(grammar1)) \
== 'I bought a bag of apples from my brother.'
assert replace(text1, extractreplacements(grammar2)) \
== 'I bought a bag of apples from T shop.'
</lang>
 
=={{header|Ruby}}==
Anonymous user