繁体   English   中英

来自文件的 Python 模式匹配

[英]Python pattern match from a file

专家们,我只是想匹配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。

除此之外,实际的正则表达式与您的输入数据并不真正匹配(例如,您试图匹配一些不在输入数据中的" 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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM