簡體   English   中英

將 python 文件導入 Jupyter Notebook

[英]Import python file to Jupyter Notebook

作為帶有擴展名.py 的 python 文件,代碼在這樣的行中

import requests
import hashlib

x=10
y=20
w=30

z=x+y

print(z)

正如您所注意到的,每個塊之間都有一個空行。 如何將這樣的 python 代碼導入 Jupyter Notebook 以便使單元格中的每個塊都像這樣在此處輸入圖像描述

我建議解析您的 *.py 文件並“手動”重新創建 *.ipynb 文件:

  1. 通過在僅存在\n的行處分隔文件來區分塊;
  2. 將每個塊的行添加到:
{
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    # Here goes your lines
    "x = 2\n",
    "y = 3\n",
    ]

  1. 把所有東西放在一起之后:
}
"cells": [
  {# Block 1},
  {# Block 2},
  ...
  {# Block N},
]
}

例子

with open('py_file.py') as py_file:
    blocks = []
    next_block = []
    for line in py_file:
        if line == '\n':
            blocks.append(next_block)
            next_block = []
            pass
        else:
            next_block.append(line.strip())

cells = '''{\n  "cells": [\n'''
for i, block in enumerate(blocks):
    cells += '''  {\n   "cell_type": "code",\n'''
    cells += f'''    "execution_count": {i+1},\n'''
    cells += '''    "metadata": {},\n    "outputs": [],\n'''
    cells += '''    "source": [\n'''
    for line in block:
        cells += f'''    "{line}\\n",\n'''
    cells += '''    ]\n'''
    
cells += ' ]\n}'

print(cells)打印

{
  "cells": [
  {
   "cell_type": "code",
    "execution_count": 1,
    "metadata": {},
    "outputs": [],
    "source": [
    "import requests\n",
    "import hashlib\n",
    ]
  {
   "cell_type": "code",
    "execution_count": 2,
    "metadata": {},
    "outputs": [],
    "source": [
    "x=10\n",
    "y=20\n",
    "w=30\n",
    ]
  {
   "cell_type": "code",
    "execution_count": 3,
    "metadata": {},
    "outputs": [],
    "source": [
    "z=x+y\n",
    ]
 ]
}

嘗試這個;

使用Ctrl + Entercell mode運行代碼,例如在Jupyter Notebook中,您可以使用#%%# %%

代碼語法

#%%
import requests
import hashlib
#%%
x=10
y=20
w=30
#%%
z=x+y
#%%
print(z)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM