Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/nbconvert/preprocessors/regexremove.py: 54%
13 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-01 06:54 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-01 06:54 +0000
1"""
2Module containing a preprocessor that removes cells if they match
3one or more regular expression.
4"""
6# Copyright (c) IPython Development Team.
7# Distributed under the terms of the Modified BSD License.
9import re
11from traitlets import List, Unicode
13from .base import Preprocessor
16class RegexRemovePreprocessor(Preprocessor):
17 """
18 Removes cells from a notebook that match one or more regular expression.
20 For each cell, the preprocessor checks whether its contents match
21 the regular expressions in the ``patterns`` traitlet which is a list
22 of unicode strings. If the contents match any of the patterns, the cell
23 is removed from the notebook.
25 To modify the list of matched patterns,
26 modify the patterns traitlet. For example, execute the following command
27 to convert a notebook to html and remove cells containing only whitespace::
29 jupyter nbconvert --RegexRemovePreprocessor.patterns="['\\s*\\Z']" mynotebook.ipynb
31 The command line argument
32 sets the list of patterns to ``'\\s*\\Z'`` which matches an arbitrary number
33 of whitespace characters followed by the end of the string.
35 See https://regex101.com/ for an interactive guide to regular expressions
36 (make sure to select the python flavor). See
37 https://docs.python.org/library/re.html for the official regular expression
38 documentation in python.
39 """
41 patterns = List(Unicode(), default_value=[]).tag(config=True)
43 def check_conditions(self, cell):
44 """
45 Checks that a cell matches the pattern.
47 Returns: Boolean.
48 True means cell should *not* be removed.
49 """
51 # Compile all the patterns into one: each pattern is first wrapped
52 # by a non-capturing group to ensure the correct order of precedence
53 # and the patterns are joined with a logical or
54 pattern = re.compile("|".join("(?:%s)" % pattern for pattern in self.patterns))
56 # Filter out cells that meet the pattern and have no outputs
57 return not pattern.match(cell.source)
59 def preprocess(self, nb, resources):
60 """
61 Preprocessing to apply to each notebook. See base.py for details.
62 """
63 # Skip preprocessing if the list of patterns is empty
64 if not self.patterns:
65 return nb, resources
67 # Filter out cells that meet the conditions
68 nb.cells = [cell for cell in nb.cells if self.check_conditions(cell)]
70 return nb, resources