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

时间:2017-04-12 06:58:02

标签: python recursion count counter frequency

我试图查看第4列中字符串出现的次数。更具体地说,某些Netflow数据中出现端口号的次数。有成千上万的端口,所以除了递归之外,我不会寻找任何特定的东西。我已经使用冒号后面的数字解析了列,我希望代码检查该数字出现的次数,以便最终输出应该打印数字,它出现的次数是这样的..

[OUTPUT]

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

[CODE]

import re


frequency = {}

file = open('/Users/rojeliomaestas/Desktop/nettest2.txt', 'r')

with open('/Users/rojeliomaestas/Desktop/nettest2.txt', 'r') as infile:    
    next(infile)
    for line in infile:
        data = line.split()[4].split(":")[1]
        text_string = file.read().lower()
        match_pattern = re.findall(data, text_string)


for word in match_pattern:
    count = frequency.get(word,0)
    frequency[word] = count + 1

frequency_list = frequency.keys()

for words in frequency_list:
    print ("port:", words,"found:", frequency[words], "times.")

[FILE]

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

2 个答案:

答案 0 :(得分:0)

来自python标准库。将返回一本完全符合您要求的字典。

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

答案 1 :(得分:0)

您需要以下内容:

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.get将返回当前值或默认值(在本例中为0)。