我试图在Linux /var/log/messages
中读取一行具有特殊字符串模式的行,我在下面给出了这个行。在这个行模式中,我查看用户的电子邮件地址,比如rajeshm@noi-rajeshm.fox.com
,并使用str.partition()
方法将其分成两部分作为列表索引,并将第一部分进一步拆分为一个列表,以便于获取最后一个索引值,即用户ID,这很好用。在
我可以得到用户列表和总计数,但是我需要计算每个用户的出现次数并打印user_name: Count
,所以键和值。在
Nov 28 09:00:08 foxopt210 rshd[6157]: pam_rhosts(rsh:auth): allowed access to rajeshm@noi-rajeshm.fox.com as rajeshm
#!/usr/bin/python3
f= open("/var/log/messages")
count = 0
for line in f:
if "allowed access" in line:
count+=1
user_id = line.partition('@')[0]
user_id = user_id.split()[-1]
print(user_id)
f.close()
print("--------------------")
print("Total Count :" ,count)
当前代码的工作原理如下:
^{pr2}$当我在谷歌上搜索的时候,我想到用字典来做这个 目的和它的预期工作:
#!/usr/bin/python3
from collections import Counter
f= open("/var/log/messages")
count = 0
dictionary = {}
for line in f:
if "allowed access" in line:
user_id = line.partition('@')[0]
user_count = user_id.split()[-1]
if user_count in dictionary:
dictionary[user_count] += 1
else:
dictionary[user_count] = 1
for user_count, occurences in dictionary.items():
print(user_count, ':', occurences)
我的输出如所愿:
bash-4.1$ ./log2.py
rajeshm : 5
navit : 780
akaul : 2
pankaja : 1
vishalm : 2
我只是想看看有没有更好的方法来做这个练习。在
您可以尝试使用正则表达式并执行以下操作:
^{pr2}$当数东西时,使用^{} class 更容易。我将把解析行封装到一个生成器中:
并将其传递给
^{pr2}$Counter()
对象:它使用^{} method 提供排序输出(最常见到最少)。在
相关问题 更多 >
编程相关推荐