【发布时间】:2021-02-14 18:34:13
【问题描述】:
我想用 html 代码更新一个字符串。字符串是这样的:
textHTMLextract = 'Hello, my name is name1 name2'
我有一个包含如下变量的数据框:
import pandas as pd
variables = [{'Var': 'name1', 'Value': '<i>John</i>'},
{'Var':'name2', 'Value': '<i><b>Smith</b></i>'}]
df_variables = pd.DataFrame(variables)
这个想法是用一些 html 标记值替换字符串。 我尝试将数据框转换为 dict,然后通过 for 循环替换:
vars_dict = dict(df_variables)
for key, value in vars_dict.items():
textHTMLextract = textHTMLextract.replace(key, value)
我希望代码返回
'Hello, my name is <i>John</i> <i><b>Smith</b></i>'
最终在 html 解释器中打印为
'你好,我的名字是 John Smith'
但我得到的只是下面的错误消息:
TypeError: replace() argument 2 must be str, not Series
我错过了什么? 提前致谢。
【问题讨论】:
标签: python pandas dictionary replace