如何在Jupyter Notebook中复制粘贴多行文本输入且不自动添加\n
Jupyter Notebook 多行输入复制粘贴格式保留方案
问题场景
在Jupyter Notebook单元格中运行以下代码获取多行交互式输入时,手动逐行输入能正常保留换行,但复制粘贴多行文本时,内容会被自动拼接为空格分隔的字符串,无法保留原换行结构:
contents = [] while True: line = input() if line: contents.append(line) else: break input_text = "\n".join(contents)
示例待粘贴输入文本:
This is a multi-line input. It is good to put several lines after each other. The reason of this is a good indentation. One can use both tabs and spaces.
可行解决方法
方法1:使用sys.stdin.read()读取完整输入
input()函数在Jupyter环境中处理粘贴的多行文本时,会将换行符解析为空格,改用sys.stdin.read()可一次性读取所有输入内容,完整保留换行符:
import sys # 粘贴多行文本后,按Ctrl+D(Linux/macOS)或Ctrl+Z(Windows)结束输入 input_text = sys.stdin.read()
方法2:基于IPython原生方法处理多行输入
利用IPython的raw_input()底层实现,配合循环逻辑实现多行输入,粘贴时可正确识别换行:
contents = [] print("粘贴多行文本后,输入空行结束:") while True: line = get_ipython().raw_input() if line: contents.append(line) else: break input_text = "\n".join(contents)
方法3:使用ipywidgets提供可视化多行输入框
通过ipywidgets的文本区域组件,直接提供支持多行输入的交互框,复制粘贴时完全保留原格式:
import ipywidgets as widgets from IPython.display import display # 创建多行文本输入框 text_input = widgets.Textarea( placeholder="粘贴或输入多行文本", layout={"height": "200px", "width": "90%"} ) display(text_input) # 获取输入内容(输入完成后运行此行) input_text = text_input.value
内容的提问来源于stack exchange,提问作者keenlearner
相关产品推荐
相关产品推荐

