【问题标题】:render Displacy Entity Recognition Visualization into Plotly Dash将 Displacy Entity Recognition Visualization 渲染为 Plotly Dash
【发布时间】:2018-12-05 01:19:03
【问题描述】:

我想将 Spacy 的 Entity Recognition Visualization 渲染到 Plotly Dash 应用程序中。

用于渲染的ER Visualization的html如下:

<div class="entities" style="line-height: 2.5">
<mark class="entities" style="background: ...>
<span>...</span>
</mark>
<mark class="entities" style="background: ...>
<span>...</span>
</mark>
</div>

我尝试使用 BeautifulSoup 解析 HTML,并通过以下代码将 HTML 转换为 Dash。但是当我运行 convert_html_to_dash(html_parsed) 时,它会抛出 KeyError: 'style'

html_parsed = bs.BeautifulSoup(html, 'html.parser')

def convert_html_to_dash(el, style = None):
    if type(el) == bs.element.NavigableString:
        return str(el)
    else:
        name = el.name
        style = extract_style(el) if style is None else style
        contents = [convert_html_to_dash(x) for x in el.contents]
    return getattr(html,name.title())(contents, style=style)

def extract_style(el):
    return {k.strip():v.strip() for k,v in [x.split(": ") for x in 
el.attrs["style"].split(";")]}

【问题讨论】:

    标签: html plotly render spacy plotly-dash


    【解决方案1】:

    并非每个标签都有style 属性。对于不存在的标签,您正在尝试访问 attrs 字典中不存在的键。 Python 的回复是KeyError

    如果您改用get(),它将返回一个默认值,而不是引发KeyError。您可以指定一个默认值作为get() 的第二个参数:

    return { k.strip() : v.strip() for k, v in
                 [ x.split(': ') for x in el.attrs.get('style', '').split(';') ]
           }
    

    这里我选择了空字符串作为默认值。

    仅通过此更改,您的代码仍然有些脆弱。如果输入与您的预期不完全匹配怎么办?

    一方面,冒号后面可能没有空格。将 split(': ') 更改为 split(':') 将使其即使没有空间也可以工作 - 如果有一个空间,它将被删除,因为您在拆分后调用 strip()

    如果在';' 上拆分后,您收到的不是列表中的键值对怎么办?最好检查它是否是一个有效的对(只包含一个冒号),否则跳过它。

    你的代码变成:

    return { k.strip() : v.strip() for k, v in
                 [ x.split(':') for x in el.attrs.get('style', '').split(';')
                   if x.count(':') == 1 ] }
    

    请注意,我选择了单引号。您的代码同时使用两者,但最好选择一个并坚持使用。

    【讨论】:

    • 这真的很有帮助。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 2020-03-07
    相关资源
    最近更新 更多