我是新来的Python,并遵守从具有其出现在文件中的一个元素,它在文件中的频率这样正则表达式来查找匹配列表中的元素
('95.108.240.252', 9)
文件的项目列表
其主要的IP地址,我收集。我想输出是这样,而不是
IP Frequency
95.108.240.252 9
我试图通过regexing列表项和打印的,但它返回下面的错误,当我尝试TypeError: expected string or bytes-like object
这要做到这一点的地址和频率是我使用做的所有现在的代码:
ips = [] # IP address list
for line in f:
match = re.search("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", line) # Get all IPs line by line
if match:
ips.append(match.group()) # if found add to list
from collections import defaultdict
freq = defaultdict(int)
for i in ips:
freq[i] += 1 # get frequency of IPs
print("IP\t\t Frequency") # Print header
freqsort = sorted(freq.items(), reverse = True, key=lambda item: item[1]) # sort in descending frequency
for c in range(0,4): # print the 4 most frequent IPs
# print(freqsort[c]) # This line prints the item like ('95.108.240.252', 9)
m1 = re.search("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", freqsort[c]) # This is the line returning errors - trying to parse IP on its own from the list
print(m1.group()) # Then print it
不是想即使解析频率呢,只是想将IP地址为起点
'freqsort [c]'是元组 – rock321987
哪条线会抛出错误BitFlow?正如're.search'导致问题,或者一般哪一行? – DuckPuncher
'('95 .108.240.252',9)'是否出现在一行上 –