Python dash - How to highlight / bold specific words in a row

Viewed 1956

I've created a table and for each row there is a specific word that needs to be highlighted.

So as an example the words in <b> should be bold (example underscored):

underscore of what to highlight

My code for creating a table and trying to make specific words bold is as follows:

import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_table
...

remove_common_words_list = ["iraq", "america"]
words = { "iraq": { "occurrences":63, 
                    "documents":{ "doc3,txt", "doc2.txt", "doc1.txt", "doc5.txt",
                    "sentences":["And when all else fails, when Katrina happens, or the death toll in Iraq mounts, we've been told that our crises are somebody else's fault.", 'But all of this cannot come to pass until we bring an end to this war in Iraq.'] },
          "america": { "occurrences":46, 
                    "documents":{ "doc3,txt", "doc1.txt", "doc5.txt",
                    "sentences":['And I accepted the job, sight unseen, motivated then by a single, simple, powerful idea that I might play a small part in building a better America.', 'It was here, in Springfield, where I saw all that is America converge farmers and teachers, businessmen and laborers, all of them with a story to tell, all of them seeking a seat at the table, all of them clamoring to be heard.'] }

remove_common_words = { "Word (Total Occurrences)":[], "Documents":[],  "Sentences containing the word":[] }
for index, word in enumerate(remove_common_words_list[0:1]):
    remove_common_words["Word (Total Occurrences)"].append(f"{word} ({words[word]['occurrences']})")
    remove_common_words["Documents"].append(", ".join(words[word]["documents"]))
    remove_common_words["Sentences containing the word"].append(re.sub(r"(" + word + ")", r"<b>\1</b>", "\n\n".join(words[word]["sentences"]), flags=re.IGNORECASE))

data = pd.DataFrame(remove_common_words)

app = dash.Dash(__name__)
app.layout = html.Div([
    dash_table.DataTable(
        id='table',
        columns=[{"name": i, "id": i} for i in data.columns],
        data=data.to_dict('records'),
        style_cell={
            'whiteSpace': 'pre-line',
            'textAlign': 'left',
            'vertical-align':'top'
        },
        style_data_conditional=[
            {
                'if': {'row_index': 'odd'},
                'backgroundColor': 'rgb(248, 248, 248)'
            }
        ],
        style_header={
            'fontWeight': 'bold'
        }
    )
])

app.run_server(debug=True)

HTML doesn't seem to be being passed, I can see markdown is an option but I've been unable to get it working and unsure how (if it can) be implemented.

So my questions is how can you make specific pieces of text bold or highlighted?

1 Answers

This answer uses Markdown in Dash, as I don't think HTML rendering is supported (see this Github Issue).

First, change line 23 in your example to

remove_common_words["Sentences containing the word"].append(re.sub(r"(" + word + ")", r"**\1**", "\n\n".join(words[word]["sentences"]), flags=re.IGNORECASE))

to follow the Markdown syntax for bolding.

Next, specify that the Table should parse the text as Markdown by updating line 31

columns=[{"name": i, "id": i, "type": 'text', "presentation": 'markdown'} for i in data.columns]

And those specified words should be bolded

enter image description here

Related