【问题标题】:How to get line breaks in a callback function (%s or .format)如何在回调函数中获取换行符(%s 或 .format)
【发布时间】:2019-12-20 08:39:39
【问题描述】:

我正在开发一个 Dash 网络应用程序,其想法是能够根据选定的模型和通过 daq 滑块作为输入给出的一些值来预测结果。

模型的选择(从下拉菜单中)和预测的返回(返回已选择的模型、预测的类别(是/否)以及是和否的百分比概率)有效好。我的问题是我希望返回的结果用换行符分隔 - 但它会将结果作为一个长段落返回。

回调,看起来像这样(简化版本 + 不包含滑块和下拉菜单的代码):

@callback(Output('slider-container', 'children'),
         [Input('model-dropdown', 'value'), 
          Input('v1', 'value'), 
          Input('v2', 'value')]

def predict_function(m, v1, v2):
    model = models[m]
    X_new = np.array([v1, v2])
    y_pred = model.predict(X_new)
    y_proba = model.predict_proba(X_new)*100
    df_proba = pd.DataFrame({'Yes': y_proba[:, 0], 'No': y_proba[:, 1]})
    yes = np.round(pd_proba.iloc[0]['Yes'], decimals=5)
    no = np.round(pd_proba.iloc[0]['No'], decimals=5)
    for i in range(len(X_new)):
        return "Model: %s \n" \
               "Prediction: %s \n" \
               "Probability for Yes: %s \n" \
               "Probability for No: %s \n" \ 
               %(m, y_pred[i], yes, no)

产生类似这样的结果(在 dash 网络应用程序中):

Model: <m> Prediction: <y_pred> Probability for Yes: <yes> Probability for No: <no>

而不是想要的结果:

Model: <m> 
Prediction: <y_pred> 
Probability for Yes: <yes> 
Probability for No: <no>

我尝试使用一个简单的示例重现该问题。在这里它在结果中返回 \n (它不会在 Dash 应用程序中返回 \n - 它只是忽略 \n 因为它不存在)。我用 %s 和 .format 都试过了:

def calc_x(x):
    y = x+2
    z = y+5
    return "X: %s \n Y: %s \n Z: %s" % (x, y, z)

calc_x(5)
# 'X: 5 \n Y: 7 \n Z: 12'

def calc_x(x):
    y = x+2
    z = y+5
    return ('X: {} \n Y: {} \n Z: {}').format(x, y, z)
# 'X: 5 \n Y: 7 \n Z: 12'

calc_x(5)


def calc_x(x):
    y = x+2
    z = y+5
    return ('X: {}\nY: {}\nZ: {}').format(x, y, z)

calc_x(5)
# 'X: 5\nY: 7\nZ: 12'

有谁知道如何解决这个问题?

【问题讨论】:

  • 尝试使用html.Br()
  • HTML 需要 &lt;br&gt; 而不是 \n 以将其显示为新行。或者您必须在 &lt;pre&gt;Text&lt;/pre&gt; 中输入文本以显示带有 \n 的新行 - 但它使用等宽字体来显示它 - 就像您问题中的代码一样。
  • 尝试将“return”更改为“print”(不要忘记括号)
  • return 语句中的 html.Br() 放在引号之外时会导致 Synthax 错误。在引号内,它只是将 html.Br() 打印为应用程序输出的一部分。

  • 替换 \n 会导致
    作为应用程序输出的一部分打印(\n 不会作为输出的一部分打印 - 也不会导致想要换行符)。使用
    Text
    建议时也会发生同样的情况(它被打印为输出的一部分)。

标签: python callback string-formatting plotly-dash


【解决方案1】:

将以下内容添加到您的退货声明中

return (html.P(["Model:{}".format(m),html.Br(),"Prediction:{}".format(y_pred[i]),html.Br(),"Probability for Yes:{}".format(yes),html.Br(),"Probability for No:{}".format(no)]))

希望这行得通。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2022-08-16
    • 2013-03-15
    • 1970-01-01
    • 2022-10-25
    • 1970-01-01
    • 2013-06-03
    相关资源
    最近更新 更多