I need to create a list of questions in a jupyter notebook. Ideally I would write something like Q#. bla bla
in one cell, Q#. bla bla
in another cell, and they would be numbered correctly. Is that doable? I already asked the question on StackOverflow (https://stackoverflow.com/questions/62217075/how-to-create-a-numbered-list-across-cells-in-jupyter-notebook), but did not receive a satisfactory solution. Many thanks for any hint!
In a comment to a stackoverflow suggestion, you mention you are already cleaning the notebooks. So you probably wouldn’t mind another command in your notebook preparation pipeline?
So based on something similar to here you could make a python script with the following and then run that step in your preparation :
import nbformat as nbf
qtag = 'Q#.'
current_qnum = 1
ntbk = nbf.read("original_notebook.ipynb", nbf.NO_CONVERT)
cells_to_keep = []
for cell in ntbk.cells:
if cell.cell_type == "markdown":
if qtag in cell['source']:
cell['source'] = cell['source'].replace(qtag,f"Q{current_qnum}.",1)
current_qnum += 1
cells_to_keep.append(cell)
new_ntbk = ntbk
new_ntbk.cells = cells_to_keep
nbf.write(new_ntbk, "qnumbered_notebook.ipynb", version=nbf.NO_CONVERT)
As written, it only replaces the first qtag
it encounters in a cell. I did this because you described your cells as being different questions.
1 Like
Thanks a lot! That is a neat solution, I will keep in mind this possibility. However, I am still looking for something more interactive. Like the markdown section numbering using ToC, the numbering of equations in LaTeX, etc. Anyway, thanks again for looking into my problems!