如何在jupyter笔记本/实验室中构建简单的小部件或应用程序以交互方式从文本中提取子字符串?

时间:2019-09-23 14:32:28

标签: jupyter-notebook jupyter jupyter-lab ipywidgets

我想遍历字符串列表,在jupyter实验室中将字符串输出为纯文本,然后以交互方式突出显示子字符串以轻松获得子字符串的起始索引和长度。目的是对文本进行快速注释并获取子字符串的坐标。

使用jupyter笔记本(实验室)进行此类操作是否容易甚至可行?如果可以的话?

我看了ipywidgets,但找不到该用例的东西。

2 个答案:

答案 0 :(得分:1)

以下是RangeSlider的示例:

import ipywidgets
input_string = 'averylongstring'
widg = ipywidgets.IntRangeSlider(
    value = [0, len(input_string)],
    min=0, max=len(input_string)
)
output_widg = ipywidgets.Text()

display(widg)
display(output_widg)

def chomp_string(widg):

    start,end = tuple(widg['new'])
    output_widg.value = input_string[start: end]

widg.observe(chomp_string, names='value')

答案 1 :(得分:1)

您可以使用jp_proxy_widgets来实现。请参见以下屏幕截图: enter image description here 请注意,有关选择协议的兼容性存在警告-我仅在Mac上的Chrome上进行了测试。我也不知道为什么索引会被一个 (select_callback(startOffset+1, endOffset+1);

有关更多信息,请参见https://github.com/AaronWatters/jp_proxy_widget

编辑:这是根据要求粘贴的文本:

import jp_proxy_widget

select_widget = jp_proxy_widget.JSProxyWidget()

txt = """
Never gonna give you up.
Never gonna let you down.
Never gonna run around and
desert you.
"""

selected_text = None

def select_callback(startOffset, endOffset):
    global selected_text
    selected_text = txt[startOffset: endOffset]
    print ("Selected", startOffset, endOffset, repr(selected_text))

select_widget.js_init("""

// (Javascript) Add a text area.
element.empty()
$("<h3>please select text:</h3>").appendTo(element);
var textarea = $('<textarea cols="50" rows="5">' + txt + "</textarea>").appendTo(element);

// Attach a select handler that calls back to select_callback.
var select_handler = function(event) {;
    var target = event.target;
    var startOffset = target.selectionStart;
    var endOffset = target.selectionEnd;
    select_callback(startOffset+1, endOffset+1);
};
textarea[0].addEventListener('select', select_handler);
""", txt=txt, select_callback=select_callback)

# display the widget
select_widget.debugging_display()