文件中的Python模式匹配



专家们,我只是想匹配raw data文件中的模式,以便将未运行的服务列为html格式。

我从谷歌上得到了帮助,并使用了下面这样的东西,但它不起作用,任何帮助都将是巨大的。

代码:

Html_file= open("result1.html","w")
html_str = """
<table border=1>
<tr>
<th bgcolor=fe9a2e>Hostname</th>
<th bgcolor=fe9a2e>Service</th>
</tr>
"""
Html_file.write(html_str)
fh=open(sys.argv[1],"r")
for line in fh:
pat_match=re.match("^HostName:"s+(.*?)".*", line)
pat_match1=re.match("^Service Status:"s+(.*not.*?)".*", line)
if pat_match:
Html_file.write("""<TR><TD bgcolor=fe9a2e>""" + pat_match.group(1) + """</TD>n""")
elif pat_match1:
Html_file.write("""<TR><TD><TD>""" + pat_match1.group(2) + """</TD></TD></TR>n""")

原始数据:

HostName: dbfoxn001.examle.com
Service Status:  NTP is Running on the host dbfoxn001.examle.com
Service Status:  NSCD is not Running on the host dbfoxn001.examle.com
Service Status:  SSSD is Running on the host dbfoxn001.examle.com
Service Status:  Postfix  is Running on the host dbfoxn001.examle.com
Service Status:  Automount is Running on the host dbfoxn001.examle.com
HostName: dbfoxn002.examle.com                   SSH Authentication failed

所需结果:

Hostname                        Service
dbfoxn001.examle.com            NSCD is not Running on the host dbfoxn001.examle.com

您的第一个问题是正则表达式没有正确嵌入字符串中。您需要退出或删除有问题的"s。

除此之外,实际的正则表达式并不能真正匹配您的输入数据(例如,您正试图匹配一些不在输入数据中的"

^HostName:s*(.+)
^Service Status:s*(.+is not Running.*)

你可以在这里和这里试试。

最后,用于生成html的python代码似乎没有生成您想要的那种html。我对示例表的html应该是什么样子的假设如下:

<table border=1>
<tr>
<th bgcolor=fe9a2e>Hostname</th>
<th bgcolor=fe9a2e>Service</th>
</tr>
<tr>
<td>dbfoxn001.examle.com</td>
<td>NSCD is not Running on the host dbfoxn001.examle.com</td>
</tr>
</table>

为此,我将hostname放入自己的变量中,而不是将其写入文件中,并在每次解析状态时添加它。我还添加了丢失的最终</table>,并关闭了打开的文件:

import sys
import re
result = open("result1.html","w")
table_header = """
<table border=1>
<tr>
<th bgcolor=fe9a2e>Hostname</th>
<th bgcolor=fe9a2e>Service</th>
</tr>
"""
result.write(table_header)
input_file=open(sys.argv[1],"r")
for line in input_file:
host_match = re.match("^HostName:s*(.+)", line)
status_match = re.match("^Service Status:s*(.+is not Running.*)", line)
if host_match:
hostname = host_match.group(1)
elif status_match:
result.write("""<tr><td>""" + hostname + """</td><td>""" + status_match.group(1) + """</td></tr>n""")
result.write("""</table>"""
input_file.close()
result.close()

最新更新