【发布时间】:2021-02-13 23:05:41
【问题描述】:
我正在使用 Python 3.7.9,并且我有一些 HTML 代码,其中包含来自 pandas 表的一些数据。我想为 pandas 表中的特定数据着色,因此我想重新使用字符串标记之间的文本并将其替换为其他一些标记(它们在 Confluence 中用于以特定颜色标记文本。)
我的输入文本字符串是:
text = 'some text now important information starts decrease-123456decrease more text not to touch next marker increase7896278689increase and more text another marker decrease-12355decrease with important information'
替换字符串是:
increase = '<span style=\"color: Red;\">'+val+'</span>'
decrease = '<span style=\"color: Green;\">'+val+'</span>'
val 是要在标记之间找到的信息。
所以我的预期输出是:
output = some text now important information starts <span style=\"color: Green;\">-123456</span> more text not to touch next marker <span style=\"color: Red;\">7896278689</span> and more text another marker <span style="color: Green;">-12355</span> with important information
这是我尝试过的:
import re
text = 'some text now important information starts decrease-123456decrease more text not to touch next marker increase7896278689increase and more text another marker decrease-12355decrease with important information'
found_increase = re.findall('increase(.+?)increase', text)
found_decrease = re.findall('decrease(.+?)decrease',text)
output=''
for i, val in enumerate(found_increase):
output=text.replace('increase'+val+'increase', '<span style=\"color: Red;\">'+val+'</span>')
for i, val in enumerate(found_decrease):
output=text.replace('decrease'+val+'decrease', '<span style=\"color: Green;\">'+val+'</span>')
print(output)
我也尝试过 pandas 附带的样式方法,但 Confluence 不是真正的 HTML,因此这种方法对我不起作用。在上面的示例中,我得到以下输出:
Some text now important information starts decrease-123456decrease more text not to touch next marker increase7896278689increase and more text another marker <span style="color: Green;">-12355</span> with important information
【问题讨论】:
-
嗨,也许你可以看看文档中的 re.sub:docs.python.org/3/library/re.html。
标签: python string replace findall confluence-rest-api