2017-09-05 85 views
-3

例如,我想要顯示Dest端口號53出現多少次,並且日誌文件中有2000個數據,所以我需要顯示每個Dest港口總和。這是我的代碼:總結出現在python輸出中的字符串總數

def main(): 
    f = openfile("/Users/rin/Desktop/new sec/2017-04-18_010.082.012.003.txt") 
    if f is None: 
     print("File not found") 
     return 
    s = splitline(f) 
    for el in s: 
     if len(el) > 50: 
      p = parselog(el) 
      if "dstport" in p: 

      print("Dest Port : %s" % p["dstport"]) 
      if "app" in p: 
       print("Apps : %s" % p["app"]) 
      print("") 

輸出:

Dest Port : 53 
Apps : DNS 

Dest Port : 123 
Apps : NTP 

Dest Port : 53 
Apps : DNS 

Dest Port : 53 
Apps : DNS 

回答

0
def main(): 
    f = openfile("/Users/rin/Desktop/new sec/2017-04-18_010.082.012.003.txt") 
    if f is None: 
     print("File not found") 
     return 
    s = splitline(f) 

    # add a counter 
    counts = {} 

    for el in s: 
     if len(el) > 50: 
      p = parselog(el) 

      if "dstport" in p: 
       # increment counter 
       if p["dstport"] in counts: 
        counts[str(p["dstport"])] += 1 
       else: 
        counts[str(p["dstport"])] = 1 
       print("Dest Port : %s" % p["dstport"]) 
      if "app" in p: 
       print("Apps : %s" % p["app"]) 
      print("") 

    # output the count 
    for k, v in counts.iteritems(): 
     print 'Dest Port %s Count: %s' % (k, v) 
+0

像我有2000口這個樣子,所以我怎麼可以一個接一個,使輸出? – warezers

+0

@warezers更新,不確定關於Python 3語法 – bphi