有效计数器,用于计数python中文本文件中的错误输入尝试



我正在编写一个程序,读取一个文本文件,该文件记录了错误输入尝试的值(无论是'password <6'或'password>10个字符)。该程序水平打印列表,使其相当长,所以我想使它垂直,更容易阅读,但我不知道如何。此外,对于每个日志(密码<6或密码>10),我希望做一个计数器来说明语句在日志文件中出现了多少次,我真的不知道怎么做。

代码如下:

def main():
with open("ITWorks_password_log.txt", "r") as ITWorks_password_log:
lines = ITWorks_password_log.readlines()
time = []
pass_characters = []
for l in lines:
as_list = l.split(", ")
time.append(as_list[0])
pass_characters.append(as_list[1].replace("n", ""))
count_pw_too_small = "password < 6"
count_pw_too_large = "password > 10"
print(time)
print(pass_characters)

main()

1:文本文件示例

2021-07-22 16:24:42.843103, password < 6
2021-07-22 16:24:44.963020, password < 6
2021-07-22 16:24:49.327202, password > 10
2021-07-22 16:24:52.810838, password > 10
2021-07-22 16:24:57.057562, password > 10
2021-07-22 16:24:58.961836, password < 6
  1. 预期输出两个括号分别标有时间和错误尝试的标签少于6个字符的尝试总数大于10个字符的尝试总数

答案差不多,"只管去做";但由于您确实发布了大量代码,因此我将为您的数据结构建议另一种选择。在解析每行时,将所有原因存储在字典中。我使用defaultdict只是为了方便。

from collections import defaultdict
def main(inputfile):
with open(inputfile, "r") as f:
results = defaultdict(list)
for line in f.readlines():
timestamp, reason = line.strip().split(", ")
# you should probably read the timestamp into an actual datetime object here
results[reason].append(timestamp)

for reason, timestamps in results.items():
print ('The reason "{}" occurred {} times.'.format(reason, len(timestamps)))
main("ITWorks_password_log.txt")

原因"密码"6";发生3次。
原因"密码>10";出现3次

当然,如果您只关心计数,则不需要单独的时间戳。您可以直接将计数存储在dict或defaultdict(int)中。

如果你想把所有的数据保存在一个集合中,那么你可以把这个集合传递给其他集合。Counter来得到类似的结果,缺点是你需要对整个列表进行第二次迭代。但这没什么大不了的。这里有一个集合的例子。计数器,但不保留数据:

from collections import Counter
def records(filename):
with open(filename, "r") as f:
for line in f.readlines():
timestamp, reason = line.split(",")
yield reason.strip()
def main(filename):
counter = Counter(records(filename))
print(counter)
main("ITWorks_password_log.txt")

计数器({密码& lt;6': 3, 'password>10: 3})

相关内容

最新更新