listing20-4.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. class Handler:
  2. """
  3. An object that handles method calls from the Parser.
  4. The Parser will call the start() and end() methods at the
  5. beginning of each block, with the proper block name as a
  6. parameter. The sub() method will be used in regular expression
  7. substitution. When called with a name such as 'emphasis', it will
  8. return a proper substitution function.
  9. """
  10. def callback(self, prefix, name, *args):
  11. method = getattr(self, prefix + name, None)
  12. if callable(method): return method(*args)
  13. def start(self, name):
  14. self.callback('start_', name)
  15. def end(self, name):
  16. self.callback('end_', name)
  17. def sub(self, name):
  18. def substitution(match):
  19. result = self.callback('sub_', name, match)
  20. if result is None: match.group(0)
  21. return result
  22. return substitution
  23. class HTMLRenderer(Handler):
  24. """
  25. A specific handler used for rendering HTML.
  26. The methods in HTMLRenderer are accessed from the superclass
  27. Handler's start(), end(), and sub() methods. They implement basic
  28. markup as used in HTML documents.
  29. """
  30. def start_document(self):
  31. print('<html><head><title>...</title></head><body>')
  32. def end_document(self):
  33. print('</body></html>')
  34. def start_paragraph(self):
  35. print('<p>')
  36. def end_paragraph(self):
  37. print('</p>')
  38. def start_heading(self):
  39. print('<h2>')
  40. def end_heading(self):
  41. print('</h2>')
  42. def start_list(self):
  43. print('<ul>')
  44. def end_list(self):
  45. print('</ul>')
  46. def start_listitem(self):
  47. print('<li>')
  48. def end_listitem(self):
  49. print('</li>')
  50. def start_title(self):
  51. print('<h1>')
  52. def end_title(self):
  53. print('</h1>')
  54. def sub_emphasis(self, match):
  55. return '<em>{}</em>'.format(match.group(1))
  56. def sub_url(self, match):
  57. return '<a href="{}">{}</a>'.format(match.group(1), match.group(1))
  58. def sub_mail(self, match):
  59. return '<a href="mailto:{}">{}</a>'.format(match.group(1), match.group(1))
  60. def feed(self, data):
  61. print(data)