如何在Python3中使用pandas数据帧动态生成html字符串?

如何在Python3中使用pandas数据帧动态生成html字符串?,python,html,string,pandas,format,Python,Html,String,Pandas,Format,我有以下dataframe列: 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

我有以下dataframe列:

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循环来迭代颜色

有什么想法吗


谢谢。

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

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>'
html='

' 颜色=['40,50,78','184,49,47'] colorIdx=0 #遍历数据帧的行 对于idx,df.iterrows()中的行: #遍历关键字列中的值 对于第['keyword']行中的字符串: #将span添加到html字符串中 html+='{}'。格式(颜色[colorIdx],strVal) #切换colorIdx以在颜色之间来回切换 如果colorIdx>1,则colorIdx=0,否则为1 html+='

'
您尝试过什么?我怀疑你因为没有显示你的代码而得票。嗨,我对Stack很陌生,我不知道我必须显示我的完整代码。我以后会记住这句话:)谢谢。是的,这正是我想要的。对不起,如果我的帖子不清楚,我会在以后的问题中更改。非常感谢你!