Python统计文件中字符串的唯一出现次数
我正在尝试使用 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 地址时,把它放进一个集合里,因为集合只会保存独特的元素,最后我打印出这个集合的长度。
1 个回答
1
IPset.update(head)
>>> 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', '.'])
有个问题。这段代码不会按照你想的那样运行。你应该把每个IP地址添加到你的集合里。下面的例子会让这个更清楚: