0

I want to convert a string which represents a jupyter notebook to a string representing python program. And I met a problem that in jupyper, something like

data = pd.read_csv("tmp.csv")
data.head()

will output something, while in python program, we need to use print, like

print(data.head())

Therefore, I wonder if there any way to add 'print'.

I have a simple idea that parameters in python are consisted of 'a-zA-Z' and '_', so by checking whether the line consists only these chars, I can solve a small part of the problem. However, it's just not enough to deal with all situations.

w57
  • 1
  • 1
    I doubt this can be done automatically. `data.head()` might be a legitimate method call that takes action without returning anything to print. – Tim Roberts Mar 01 '23 at 07:32
  • https://nbdev.fast.ai/ can be used for developing and publishing packages software using jupyter notebooks. Not sure whether this is what you are looking for – Sirish Mar 01 '23 at 08:17
  • "I have a simple idea that parameters in python are consisted of 'a-zA-Z' and '_', " that is actually not true. Here are the details for what constitutes a valid identifier: https://docs.python.org/3/reference/lexical_analysis.html#identifiers but more importantly, as Tim Roberts notes, you cannot really do this in general unless you don't mind printing a bunch of useless stuff. – juanpa.arrivillaga Mar 01 '23 at 08:25

2 Answers2

0

I think you can handle this by writing sys.stdout to a text file in your program, if you want to keep the output of the entire program, whether it is a 'return' from a function or a print statement.

e.g. this answer demonstrates how to use stdout: answer with code on how to log to stdout

b_d
  • 1
  • 1
  • 1
0
def convert_jupyter_to_python(jupyter_str):
    python_str = ""
    for line in jupyter_str.splitlines():
        if not line.startswith("#"):
            if any(c.isalnum() or c == "_" for c in line):
               python_str += "print(" + line + ")\n"
            else:
                python_str += line + "\n"
    return python_str
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 05 '23 at 19:59