實習點滴(2)--python統計ip地址出現的個數

        今天,在完成任務的時候,用到了統計ip地址出現的個數,現在就做一下總結,寫一個統計ip地址的函數

        代碼如下:

        輸入:包含ip地址的文件所在的路徑

        輸出:包含ip地址和它出現的次數的一個list

def ip_items(Inputfile_path):
    #Input:a file path including some ip address
    #Output:a list including ip address and the count of it
    with codecs.open(Inputfile_path,'r',encoding='utf-8') as in_f:
         lines = in_f.readlines()
         #正則表達式的形式:'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'
         regular_expression=r'\.'.join([r'\d{1,3}']*4)
         #根據包含正則表達式的字符串創建模式對象
         schema_object=re.compile(regular_expression)
         count={}
         for line in lines:
             line = line.encode("utf-8")
             for ip in schema_object.findall(line):
                  #遍歷這一行中出現的所有的ip地址
                  count[ip]=count.get(ip,1)+1
         ip_items=count.items()
         return ip_items

       

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章