簡體   English   中英

從文件中抓取IP地址並計算出現的次數

[英]Grabbing IP addresses from a file and counting the occurences

我對python很新,在完成學校作業時遇到困難。 我應該從文件中獲取IP地址,然后計算每個IP出現的次數並打印出結果。

我一直收到錯誤:不可用類型:'list'

這是代碼:

#!/usr/bin/python
import re

def grab_ip(file):
    ips = []
    occurence = {}
    with open (file) as file:
        for ip in file:
            ips.append(re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})', ip))
        for ipaddr in ips:
            if ipaddr in occurence:
                occurence[ipaddr] = occurence[ipaddr] + 1
            else:
                occurence[ipaddr] = 1
    for key, value in occurence.iteritems():
        print key, value
    return None
print grab_ip('FILE_WITH_IPS.txt')

謝謝!

re.findall()將返回一個列表,因此請嘗試使用附加的anther循環:

#!/usr/bin/python
import re

def grab_ip(file):
    ips = []
    occurence = {}
    with open (file) as file:
        for ip in file:
            ip_data=re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})',ip)
            for i in ip_data:
                ips.append(i)
        for ipaddr in ips:
            if ipaddr in occurence:
                occurence[ipaddr] = occurence[ipaddr] + 1
            else:
                occurence[ipaddr] = 1
    for key, value in occurence.iteritems():
        print key, value
    return None
print grab_ip('data')

這是文件數據行:

123.0.9.1
fjdakl
jfkal 23.2.2.9

函數返回無

你完全在那里。 只需使用extend而不是append因為findall函數的輸出必須是一個列表。 因此,將列表附加到另一個列表將生成列表列表,這就是您收到錯誤Unhashable Type: 'list'

ips.extend(re.findall(r'\b(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\b', ip))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM