簡體   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