【问题标题】:How to dynamically generate an html string using a pandas DataFrame in Python 3?如何在 Python 3 中使用 pandas DataFrame 动态生成 html 字符串?
【发布时间】:2019-10-21 01:50:58
【问题描述】:

我有以下数据框列:

print(df['keyword'])

                   keyword
1    ['aloe gel', 'how to plant aloe']
2    ['avocado oil hair', 'best avocado oil']
3    ['2019 hairstyles']
4    ['peel off mask', 'charcoal face mask', 'charcoal powder']
5    ['nyx eyebrow pencil', 'eyebrow waxing']
6    ['matcha green']
7    ['hair growth oil']
8    ['organic coconut milk', 'organic milk', 'organic compounds']
9    ['apple vinegar cider']

我想在一个长的 HTML 字符串中传递每个 python 字符串(芦荟凝胶,如何种植芦荟等...)。

我希望输出在 HTML 中看起来像这样:

 <p style="text-align: center;"><strong>
        <span style="color: rgb(40, 50, 78);">aloe gel.</span>
        <span style="color: rgb(184, 49, 47);">how to plant aloe.</span> 
        <span style="color: rgb(40, 50, 78);">avocado oil hair.</span></strong>
    </p>

因此结果如下:

芦荟凝胶。如何种植芦荟。鳄梨油头发。

我相信我需要使用 for 循环将每个关键字添加到 HTML 字符串以及使用 for 循环来迭代颜色。

有什么想法吗?

谢谢。

【问题讨论】:

  • 你试过什么?我怀疑你因为没有显示代码而投票失败。
  • 您好,我是 Stack 的新手,我不知道我必须展示我的完整代码。我会记住这一点的:)谢谢。

标签: python html string pandas format


【解决方案1】:

我相信这应该可以满足您的需求。如果没有,你能澄清一下吗?

html = '<p style="text-align: center;"><strong>'

colors = ['40, 50, 78', '184, 49, 47']
colorIdx = 0
#iterate through rows of dataframe
for idx, row in df.iterrows():
    #iterate through values in keyword column
    for strVal in row['keyword']:
        #add the span to the html string
        html += '<span style="color: rgb({});">{}</span>'.format(colors[colorIdx], strVal)
        #switch the colorIdx to switch back and forth between colors
        colorIdx = 0 if colorIdx > 1 else 1


html += '</strong></p>'

【讨论】:

  • 是的,这正是我想要的。抱歉,如果我的帖子不清楚,我会为以后的问题更改它。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
  • 1970-01-01
  • 2021-07-15
  • 2019-06-13
  • 2020-10-12
  • 1970-01-01
  • 2017-12-13
相关资源
最近更新 更多