【问题标题】:Converting functions in Jupyter notebook (ipynb) files to individual .py files将 Jupyter notebook (ipynb) 文件中的函数转换为单个 .py 文件
【发布时间】:2019-04-16 14:32:24
【问题描述】:

如何将 ipynb 文件目录中的函数转换为单独的 .py 文件?这将使得在单片 jupyter notebook 中进行测试后很容易导入。

【问题讨论】:

    标签: python jupyter-notebook


    【解决方案1】:

    这是代码......

    # program to convert functions in cells to indivdiual .py files
    # the first line of the cell containing function to be converted should have
    # filename.py
    
    import json
    from os import listdir
    
    fs = listdir() # get the filenames
    
    # make an exclusion list
    magics = %lsmagic
    magic_words = [s for s in str(magics).split(' ') if s not in '' if '%' in s[0]]
    magic_words = [s for s in magic_words if s != '%']
    exclude = ['util.startLoop()'] + magic_words
    
    # Ignore ipynb files beginning with '_'
    ipyfilelist = [f for f in fs if f[-6:].upper() == '.IPYNB' if f[0] != '_']
    
    code_cells = []
    for file in ipyfilelist:
        with open(file) as datafile:
            code = json.load(datafile)
            code_cells.append([cell['source'] for cell in code['cells'] if cell['cell_type'] == 'code'])
    
    codes = [cell for cells in code_cells for cell in cells if cell]
    
    code_dict = {pycode[0][2:-1]:pycode for pycode in codes if pycode[0][-4:] == '.py\n'}
    
    for k, v in code_dict.items():
        with open(k, 'w') as f:
            for line in v:
                if not any(word in line for word in exclude):
                    f.write(line)
    

    【讨论】:

      【解决方案2】:

      这是一种更详细的方法,但选项仅捕获以关键字 def 开头的函数定义

          import sys,json
      #credit https://stackoverflow.com/questions/17077494/how-do-i-convert-a-ipython-notebook-into-a-python-file-via-commandline?rq=1
      def convert_ipynb(in_file,out_file,options='functions'):
          """converts an ipynb file with option for only writing function definitions
          """
          f = open(in_file,'r')  
          j = json.load(f);f.close()
          of = open(out_file, 'w')  
          function_block=False #flag for function definition block of lines
          if j["nbformat"] >=4:
                  for i,cell in enumerate(j["cells"]):
                          of.write("#cell "+str(i)+"\n")
                          #print ("#cell "+str(i)+"\n")
                          function_block=False
                          for line in cell["source"]:
                              if 'functions' in options: #filter and write only function definitons
                                  if (line.startswith('def'))  : #toggle function block flag and write to file
                                     # print(line)
                                      function_block=True
                                      of.write(line)
                                      continue #skip rest of this loop as def keyword detected
                                  if (not (line.startswith ((' ','/t','#')))): #any char other than space,tab,# ends block
                                      function_block=False
                                  if  function_block :  #if function block is true write line
                                      of.write(line)        
                                     
                              else:#functions filtering string not in options so just save all lines
                                  of.write(line)
                          of.write('\n\n')
          else:
                  for i,cell in enumerate(j["worksheets"][0]["cells"]):
                          of.write("#cell "+str(i)+"\n")
                          for line in cell["input"]:
                                  of.write(line)
                          of.write('\n\n')
      
          of.close()
      

      【讨论】:

      • 这会将所有功能捕获在单个文件中,而不是单个文件中
      【解决方案3】:

      您也可以使用魔法写入文件。 有关文档,请参阅 magic ipython。

      例如,如果您执行以下单元格:

      %%writefile my_function.py
      def my_function(x):
          return x + 2
      

      你会得到

      Writing my_function.py
      

      文件 my_function.py 将在您当前的工作目录中。

      你也可以选择 File/Download as/Python (py) 来保存整个 notebook

      【讨论】:

        猜你喜欢
        • 2016-10-14
        • 2022-06-26
        • 1970-01-01
        • 1970-01-01
        • 2021-03-22
        • 1970-01-01
        • 2019-12-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多