regexremove.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """
  2. Module containing a preprocessor that removes cells if they match
  3. one or more regular expression.
  4. """
  5. # Copyright (c) IPython Development Team.
  6. # Distributed under the terms of the Modified BSD License.
  7. import re
  8. from traitlets import List, Unicode
  9. from .base import Preprocessor
  10. class RegexRemovePreprocessor(Preprocessor):
  11. """
  12. Removes cells from a notebook that match one or more regular expression.
  13. For each cell, the preprocessor checks whether its contents match
  14. the regular expressions in the `patterns` traitlet which is a list
  15. of unicode strings. If the contents match any of the patterns, the cell
  16. is removed from the notebook.
  17. To modify the list of matched patterns,
  18. modify the patterns traitlet. For example, execute the following command
  19. to convert a notebook to html and remove cells containing only whitespace::
  20. jupyter nbconvert --RegexRemovePreprocessor.patterns="['\\s*\\Z']" mynotebook.ipynb
  21. The command line argument
  22. sets the list of patterns to ``'\\s*\\Z'`` which matches an arbitrary number
  23. of whitespace characters followed by the end of the string.
  24. See https://regex101.com/ for an interactive guide to regular expressions
  25. (make sure to select the python flavor). See
  26. https://docs.python.org/library/re.html for the official regular expression
  27. documentation in python.
  28. """
  29. patterns = List(Unicode(), default_value=[]).tag(config=True)
  30. def check_conditions(self, cell):
  31. """
  32. Checks that a cell matches the pattern.
  33. Returns: Boolean.
  34. True means cell should *not* be removed.
  35. """
  36. # Compile all the patterns into one: each pattern is first wrapped
  37. # by a non-capturing group to ensure the correct order of precedence
  38. # and the patterns are joined with a logical or
  39. pattern = re.compile('|'.join('(?:%s)' % pattern
  40. for pattern in self.patterns))
  41. # Filter out cells that meet the pattern and have no outputs
  42. return not pattern.match(cell.source)
  43. def preprocess(self, nb, resources):
  44. """
  45. Preprocessing to apply to each notebook. See base.py for details.
  46. """
  47. # Skip preprocessing if the list of patterns is empty
  48. if not self.patterns:
  49. return nb, resources
  50. # Filter out cells that meet the conditions
  51. nb.cells = [cell for cell in nb.cells if self.check_conditions(cell)]
  52. return nb, resources