计算字符串在特定列中出现的次数

2024-05-20 07:16:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道一个字符串在第4列中出现了多少次。更具体地说,端口号在某些Netflow数据中出现的次数。有数以千计的端口,所以我不寻找任何具体的东西,除了递归。我已经用冒号后面的数字解析了这个列,我希望代码检查这个数字出现了多少次,所以最终输出应该打印出这个数字,并显示它出现的次数。。在

[输出]

Port: 80 found: 3 times.
Port: 53 found: 2 times.
Port: 21 found: 1 times.

[代码]

^{pr2}$

[文件]

Date first seen          Duration Proto      Src IP Addr:Port          Dst IP Addr:Port   Packets    Bytes Flows
2017-04-02 12:07:32.079     9.298 UDP            8.8.8.8:80 ->     205.166.231.250:8080     1      345     1
2017-04-02 12:08:32.079     9.298 TCP            8.8.8.8:53 ->     205.166.231.250:80       1       75     1
2017-04-02 12:08:32.079     9.298 TCP            8.8.8.8:80 ->     205.166.231.250:69       1      875     1
2017-04-02 12:08:32.079     9.298 TCP            8.8.8.8:53 ->     205.166.231.250:443      1      275     1
2017-04-02 12:08:32.079     9.298 UDP            8.8.8.8:80 ->     205.166.231.250:23       1      842     1
2017-04-02 12:08:32.079     9.298 TCP            8.8.8.8:21 ->     205.166.231.250:25       1      146     1

Tags: 数据端口字符串代码ipport数字次数
2条回答

来自python标准库。将返回一本词典,其中包含您要查找的内容。在

from collections import Counter
counts = Counter(column)
counts.most_common(n) # will return the most common values for specified number (n)

你需要这样的东西:

frequency = {}
with open('/Users/rojeliomaestas/Desktop/nettest2.txt', 'r') as infile:    
    next(infile)
    for line in infile:
        port = line.split()[4].split(":")[1]
        frequency[port] = frequency.get(port,0) + 1

for port, count in frequency.items(): 
    print("port:", port, "found:", count, "times.")

其核心是保留端口的dict来计数,并为每一行增加这个值。dict.get将返回当前值或默认值(在本例中为0)。在

相关问题 更多 >