2016-10-05 86 views
-2

我上線re.search錯誤。如何讀取所有IP地址在一個文本文件,並遍歷每個IP地址只有一次

def search(pattern, string, flags=0): 
"""Scan through string looking for a match to the pattern, returning 
    a match object, or None if no match was found.""" 
return _compile(pattern, flags).search(string) 

代碼:

def IP(): 
file = open('mbox.txt' , 'r') 
count = 0 
for line in file: 
    address = re.search(r"\b\d{1,3}\. \d{1,3}\. d{1,3}\. \d{1,3}\b", file) 
    for line in address: 
     ip = address 
     if line != allIPS: 
      ip.add(ip) 
      ip.add('\n') 
      count = count +1 
return (count) 

def main(): 
    #global statement for fhand 
    print("This program does the folowing: ") 
    print("The sum of lines in the file: %d " % (lineCount())) 
    print("The number of messages in the file: %d " % (MsgCount())) 
    print("All IP Addresses: %d\n " % (IP() )) 

if __name__ == '__main__': 
main() 
+1

始終顯示完整的錯誤消息。 – furas

+0

作爲一個頭,你正在重複使用'行'在每個for循環,應該是唯一的每一個。 – CasualDemon

+0

一行中可以有多個IP地址嗎? – tdelaney

回答

0

我看到一個錯誤 - 你需要line而不是filere.search()

1

你的正則表達式中有多餘的空間,將讓你從匹配點IPv4地址和你如何嘗試迭代線路有問題。試試這個:

def IP(): 
    # use a set to maintain unique addresses. no need to check if the 
    # address is in the set because duplicates are automatically removed 
    # during add. 
    allIPS = set() 

    # open with a context manager for automatic close. You dont need to 
    # specify the mode because "r" is the default. 
    with open('mbox.txt') as myfile: 

     # now iterate the lines 
     for line in myfile: 

      # use findall to find all matches in the line and 
      # update the set 
      allIPS.update(
       re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", 
        line)) 

    # it seems like all you care about is the number of unique addresses 
    return len(allIPS) 
+0

非常感謝!但現在當我運行該程序所有IP地址只是給了我0. –

+0

看起來像正則表達式中的一個缺少反斜槓。我已經修復了代碼。 – tdelaney

+0

我不想成爲一個痛苦,但我仍然得到相同的結果 –