簡體   English   中英

Python計算文件中字符串的唯一出現次數

[英]Python counting the unique occurences of a string in a file

我正在嘗試使用python 3.3.1計算Apache日志文件中的唯一IP地址。問題是我認為它不能正確計數所有內容。

這是我的代碼:

import argparse
import os
import sys
from collections import Counter

#
# This function counts the unique IP adresses in the logfile
#
def print_unique_ip(logfile):
    IPset = set()
    for line in logfile:
        head, sep, tail = line.partition(" ")
        if(len(head) > 1):
            IPset.update(head)

    print(len(IPset))
    return  

#
# This is the main function of the program
#
def main():
    parser = argparse.ArgumentParser(description="An appache log file processor")

    parser.add_argument('-l', '--log-file', help='This is the log file to work on', required=True)
    parser.add_argument('-n', help='Displays the number of unique IP adresses', action='store_true')
    parser.add_argument('-t', help='Displays top T IP adresses', type=int)
    parser.add_argument('-v', help='Displays the number of visits of a IP adress')

    arguments = parser.parse_args()

    if(os.path.isfile(arguments.log_file)):
        logfile = open(arguments.log_file)
    else:
        print('The file <', arguments.log_file, '> does not exist')
        sys.exit

    if(arguments.n == True):
        print_unique_ip(logfile)
    if(arguments.t):
        print_top_n_ip(arguments.t, logfile)
    if(arguments.v):
        number_of_ocurrences(arguments.v, logfile)

    return


if __name__ == '__main__':
  main()

我已經把其他所有東西都留了。

當我運行它時,我得到

$ python3 assig4.py -l apache_short.log -n
12

但我知道文件中有12個以上的唯一IP

它似乎沒有給我正確的結果。 我要做的是逐行讀取文件,然后在找到IP地址時將其放入集合中,因為它僅保存唯一元素,然后打印出所述集合的長度。

IPset.update(head)

錯誤。 這不會達到您的期望。 您想add每個IP add到您的集合中。 例子最清楚:

>>> s1 = set()
>>> s2 = set()
>>> s1.add('11.22.33.44')
>>> s2.update('11.22.33.44')
>>> s1
set(['11.22.33.44'])
>>> s2
set(['1', '3', '2', '4', '.'])

暫無
暫無

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

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