Home
Locate
CS 101
CS 496
Login
Tutors
Marks
About
Send
Close
Add comments:
(status displays here)
Got it!
This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.
nbsp; Note: This appears on each machine/browser from which this site is accessed.
String rewriting examples
by RS
admin@ycp.powersoftwo.org
c
go
java
js
lua
py
vbs
rkt
scm
pro
1. String rewriting examples
2. String rewriting examples
Here is an abstracted example of a string rewriting system using percent signs.
3. Python code
Here is the Python code.
import re envPat1 = r"(.*?)%([A-Z][A-Z0-9]*)%(.*)" envReg1 = re.compile(envPat1) def envEval1(text1, envDict1): text2 = "" while True: match1 = envReg1.search(text1) if not match1: return text2 + text1 prefix1 = match1.group(1) name1 = match1.group(2) suffix1 = match1.group(3) text2 += prefix1 text3 = envDict1[name1] text2 += text3 text1 = suffix1 return text2 def srsTestDo1(): textList1 = [ "before %ALPHA% middle %BETA% after ", "start %ALPHA% continue %BETA% end" ] envDict1 = { "ALPHA" : "(alpha pattern)", "BETA" : "(beta pattern)" } n1 = len(textList1) print("(begin list of {0:d} lines)".format(n1)) for i1 in range(0,n1): print("{0:d}:".format(i1)) text1 = textList1[i1] text2 = envEval1(text1,envDict1) print("\tbefore: \"{0:s}\"".format(text1)) print("\tafter: \"{0:s}\"".format(text2)) print("(end list of {0:d} lines)".format(n1)) srsTestDo1()
4. Python output
Here is the output of the Python code.
(begin list of 2 lines) 0: before: "before %ALPHA% middle %BETA% after " after: "before (alpha pattern) middle (beta pattern) after " 1: before: "start %ALPHA% continue %BETA% end" after: "start (alpha pattern) continue (beta pattern) end" (end list of 2 lines)
5. End of page
by RS
admin@ycp.powersoftwo.org