jupyter+notebook中str.split
时间: 2023-12-25 11:29:14 浏览: 79
在Jupyter Notebook中,可以使用str.split()方法将字符串拆分为多个子字符串,并返回一个列表。该方法可以接受一个可选的参数,用于指定分隔符,默认情况下使用空格作为分隔符。
以下是一个示例演示如何在Jupyter Notebook中使用str.split()方法:
```python
# 定义一个字符串
string = "Hello World"
# 使用split()方法拆分字符串
result = string.split()
# 打印拆分后的结果
print(result) # 输出:['Hello', 'World']
```
在上述示例中,我们定义了一个字符串"Hello World",然后使用split()方法将其拆分为两个子字符串,并将结果存储在一个列表中。最后,我们打印出拆分后的结果。
相关问题
jupyter notebook水果识别
### 使用深度学习在 Jupyter Notebook 中实现水果识别
#### 准备工作环境
为了能够在 Jupyter Notebook 中顺利运行代码,需要安装必要的库。这通常包括 TensorFlow 或 PyTorch 这样的深度学习框架以及用于图像处理的 OpenCV 和 Pillow 库。
```bash
pip install tensorflow opencv-python pillow matplotlib scikit-learn
```
#### 加载并预处理数据集
获取一个合适的水果图片数据集对于训练模型至关重要。可以使用公开的数据集如 CIFAR-10 的变种或其他专门针对水果分类的数据集。加载这些数据之后,要对其进行标准化和其他形式的预处理以便于后续建模过程[^1]。
```python
import os
from PIL import Image
import numpy as np
from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
def load_fruit_data(directory, img_size=(64, 64)):
images = []
labels = []
label_dict = {name: idx for idx, name in enumerate(os.listdir(directory))}
for fruit_name in os.listdir(directory):
path = os.path.join(directory, fruit_name)
if not os.path.isdir(path): continue
for file in os.listdir(path):
try:
image_path = os.path.join(path, file)
with Image.open(image_path).convert('RGB') as img:
resized_img = img.resize(img_size)
images.append(np.array(resized_img))
labels.append(label_dict[fruit_name])
except Exception as e:
print(f"Error loading {image_path}: ", str(e))
X = np.array(images) / 255.0
y = to_categorical(labels)
return train_test_split(X, y, test_size=0.2, random_state=42)
train_X, val_X, train_y, val_y = load_fruit_data('./path/to/your/dataset')
print("Data loaded and preprocessed.")
```
#### 构建卷积神经网络 (CNN) 模型
构建适合解决多类别分类问题的 CNN 结构。这里采用了一个简单的架构作为例子;实际应用中可能需要更复杂的配置以获得更好的性能表现[^3]。
```python
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
model = Sequential([
Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(64, 64, 3)),
MaxPooling2D(pool_size=(2, 2)),
Conv2D(64, kernel_size=(3, 3), activation='relu'),
MaxPooling2D(pool_size=(2, 2)),
Flatten(),
Dense(128, activation='relu'),
Dropout(0.5),
Dense(len(train_y[0]), activation='softmax') # 输出层节点数等于标签种类数量
])
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.summary()
```
#### 训练模型
设置好超参数后就可以开始训练了。考虑到计算资源有限,在本地环境中建议先尝试较小规模的数据子集来进行调试和验证。
```python
history = model.fit(
train_X,
train_y,
epochs=10,
batch_size=32,
validation_data=(val_X, val_y)
)
```
#### 测试与评估
完成训练后应当对测试集上的预测效果做出评价,并据此调整优化策略或改进现有方案。
```python
test_loss, test_acc = model.evaluate(val_X, val_y)
print(f'Test accuracy: {test_acc:.4f}')
```
jupyter notebook cell前序号
### 显示或设置 Jupyter Notebook 中 Cell 的前序号
在 Jupyter Notebook 中,默认情况下并不会自动为每个 cell 添加编号。然而,当安装并启用了 `Table of Contents (2)` 扩展之后,可能会遇到自动生成的标题带有不想要的数字序号的情况[^1]。
对于希望控制或显示 cell 前面的特定序号的需求,可以通过以下几种方式实现:
#### 方法一:通过 Table of Contents (2) 插件配置
如果使用的是 `Table of Contents (2)` 插件导致了不必要的序号,则可以在插件选项中调整其行为来移除这些序号。具体做法是在菜单栏找到 `Table of Contents` -> `Settings`,然后关闭 "Number sections" 功能。
#### 方法二:手动添加 Markdown 序号
另一种方法是直接在 Markdown 单元格内手工输入所需的序号作为章节标记的一部分。这种方式允许完全定制化每一段落之前的编号形式,并且不会受到任何扩展的影响。例如,在 Markdown 单元格中键入如下内容:
```markdown
# 0. Introduction
This is an introduction section.
```
这样就可以确保每次渲染时都按照指定的方式展示序号。
#### 方法三:利用第三方库辅助管理
还可以考虑借助一些 Python 包如 `nbformat` 来批量修改 notebook 文件中的 cell 属性,从而达到统一管理和设定 cell 编号的效果。下面是一个简单的例子说明如何读取和写回含有新编排好的 cell 序号的 .ipynb 文件:
```python
import nbformat as nbf
def add_custom_numbering(notebook_path, output_path=None):
"""Add custom numbering to markdown cells."""
# Load the notebook
with open(notebook_path) as f:
nb = nbf.read(f, as_version=4)
counter = 1
for idx, cell in enumerate(nb.cells):
if 'markdown' == cell['cell_type']:
title_level = cell['source'].strip().startswith('#')
if title_level and not cell['source'].strip().endswith('.'):
prefix = str(counter)+'. '
new_source_lines = []
lines = cell['source'].split('\n')
for line in lines:
if line.startswith('#'):
line = '#' * len(line.split(' ')[0]) + ' ' + prefix + ' '.join(line.split(' ')[1:])
new_source_lines.append(line)
cell['source'] = '\n'.join(new_source_lines).replace(prefix, '', 1)
counter += 1
# Write back out the modified notebook
if output_path is None:
output_path = notebook_path
with open(output_path, mode='wt') as f:
nbf.write(nb, f)
add_custom_numbering('./example_notebook.ipynb', './numbered_example_notebook.ipynb')
```
这段脚本遍历给定路径下的笔记本文件内的所有单元格,仅对那些被认为是标题级别的 Markdown 文本应用自定义编号逻辑[^3]。
阅读全文
相关推荐















