我有如下代码,其中我过滤出比2天大的日期,并使其变粗并更改颜色。
在这种情况下,我还想将警告替换为 失败 ,因为发现日期早于2天。
任何人都可以通过下面的代码来帮助我们实现这一目标。
import re
from datetime import datetime
ht ="""<tr>
<td>32356</td>
<td>cfra03</td>
<td>04-07-2020</td>
<td>Ssv</td>
<td>Warning</td>
</tr>
<tr>
<td>32367</td>
<td>c017</td>
<td>04-08-2020</td>
<td>SDR</td>
<td>Completed</td>
</tr>
<tr>
<td>29451</td>
<td>c10</td>
<td>04-05-2020</td>
<td>SR</td>
<td>Warning</td>
</tr>
"""
date_var = re.findall(r"[\d]{2}-[\d]{2}-[\d]{4}", ht)
for s in date_var:
element_date = datetime.strptime(s, "%m-%d-%Y")
if (datetime.now() - element_date).days > 2:
ht = ht.replace(s, '<b><font color="#ff0000">'+s+'</font></b>')
print (ht)
当前输出为-
<tr>
<td>32356</td>
<td>cfra03</td>
<td>04-07-2020</td>
<td>Ssv</td>
<td>Warning</td>
</tr>
<tr>
<td>32367</td>
<td>c017</td>
<td>04-08-2020</td>
<td>SDR</td>
<td>Completed</td>
</tr>
<tr>
<td>29451</td>
<td>c10</td>
<td><b><font color="#ff0000">04-05-2020</font></b></td>
<td>SR</td>
<td>Warning</td>
</tr>
输出应为-
<tr>
<td>32356</td>
<td>cfra03</td>
<td>04-07-2020</td>
<td>Ssv</td>
<td>Warning</td>
</tr>
<tr>
<td>32367</td>
<td>c017</td>
<td>04-08-2020</td>
<td>SDR</td>
<td>Completed</td>
</tr>
<tr>
<td>29451</td>
<td>c10</td>
<td><b><font color="#ff0000">04-05-2020</font></b></td>
<td>SR</td>
<td><b><font color="#ff0000">Failed</font></b></td>
</tr>
'''
答案 0 :(得分:0)
此代码:
import re
from datetime import datetime
ht ="""<tr>
<td>32356</td>
<td>cfra03</td>
<td>04-07-2020</td>
<td>Ssv</td>
<td>Warning</td>
</tr>
<tr>
<td>32367</td>
<td>c017</td>
<td>04-08-2020</td>
<td>SDR</td>
<td>Completed</td>
</tr>
<tr>
<td>29451</td>
<td>c10</td>
<td>04-05-2020</td>
<td>SR</td>
<td>Warning</td>
</tr>
"""
result = []
rows = ht.split('<tr>')
for row in rows :
date_var = re.findall(r"[\d]{2}-[\d]{2}-[\d]{4}", row, re.DOTALL)
for s in date_var:
element_date = datetime.strptime(s, "%m-%d-%Y")
if (datetime.now() - element_date).days > 2:
row = row.replace(s, '<b><font color="#ff0000">'+s+'</font></b>')
row = row.replace( 'Warning', 'Failed') # or whatever
result.append(row)
print ('<tr>'.join(result))
给出以下结果:
<tr>
<td>32356</td>
<td>cfra03</td>
<td>04-07-2020</td>
<td>Ssv</td>
<td>Warning</td>
</tr>
<tr>
<td>32367</td>
<td>c017</td>
<td>04-08-2020</td>
<td>SDR</td>
<td>Completed</td>
</tr>
<tr>
<td>29451</td>
<td>c10</td>
<td><b><font color="#ff0000">04-05-2020</font></b></td>
<td>SR</td>
<td>Failed</td>
</tr>
您可以根据需要在Failed
周围添加HTML。