一点逻辑数学noob问题...
我正在解析ip地址和用户名的日志文件。
我用它来避免写重复的条目:
If Duplicate(strIP) = False Then LOG strIP & vbTab & strUser
If Duplicate(strUser) = False Then LOG strIP & vbTab & strUser
目前,我可以通过调用此函数来避免重复记录:
Function Duplicate(strArg)
Duplicate = Flase
Set ReadLogFile = objFSO.OpenTextFile(strLogFile,1,False)
If Instr(ReadLogFile.ReadAll,strArg) Then
Duplicate = True
End If
ReadLogFile.Close
End Function
这会读取我写的文件。
我的问题是: 通过将先前的值保存在内存中而不是在文件中搜索字符串,是否可以动态检查是否存在重复项?我正在解析的日志已按顺序排序。
例如,像这样:
strIP = HOLDstrIP
strUser = HOLDstrUser
If strIP <> HOLDstrIP Then
'the current string <> the previous (hold) string, so log it.
Else
'the values are the same. Increment a counter by 1
End If
最后,我想要一个重复的IP地址数和重复用户名的总数。
我希望这不是太模糊,我相信之前有人这样做了!
谢谢你们。
答案 0 :(得分:1)
使用词典:
选项明确
Dim dicSeen : Set dicSeen = CreateObject("Scripting.Dictionary")
Dim aFakeLog : aFakeLog = Split("f f a b a c d e f a b")
Dim sToken
WScript.Echo Join(aFakeLog)
WScript.Echo "--------------"
For Each sToken In aFakeLog
If Not dicSeen.Exists(sToken) Then
WScript.Echo sToken, "seen for the first time"
End If
dicSeen(sToken) = dicSeen(sToken) + 1
Next
WScript.Echo "--------------"
Dim sType
For Each sType In dicSeen.Keys()
WScript.Echo sType, dicSeen(sType)
Next
输出:
cscript 21272514.vbs
f f a b a c d e f a b
--------------
f seen for the first time
a seen for the first time
b seen for the first time
c seen for the first time
d seen for the first time
e seen for the first time
--------------
f 3
a 3
b 2
c 1
d 1
e 1
更新评论:
使用功能:
Option Explicit
Function firstTimeSeen(dicX, sVal)
firstTimeSeen = Not dicX.Exists(sVal)
dicX(sVal) = dicX(sVal) + 1
End Function
Dim dicSeen : Set dicSeen = CreateObject("Scripting.Dictionary")
Dim aFakeLog : aFakeLog = Split("f f a b a c d e f a b")
Dim sToken
WScript.Echo Join(aFakeLog)
WScript.Echo "--------------"
For Each sToken In aFakeLog
If firstTimeSeen(dicSeen, sToken) Then
WScript.Echo sToken, "seen for the first time"
End If
Next
WScript.Echo "--------------"
Dim sType
For Each sType In dicSeen.Keys()
WScript.Echo sType, dicSeen(sType)
Next
答案 1 :(得分:0)
好吧,我已经完成了使用词典所需的任务!
@ Ekkehard.Horner,在没有你帮助的情况下,我仍然会为此苦苦挣扎。
以下是我用来获取所需结果的相关代码:
For myParsing In myLog
strIP = 'The parsed IP
strUser = 'The parsed user
If Not IsEmpty(HOLDstrIP) And strIP <> HOLDstrIP Then CountThemOut
objDict(strIP) = objDict(strIP) + 1
objDict(strUser) = objDict(strUser) + 1
HOLDstrIP = strIP
Next
Sub CountThemOut
Dim item
For Each item In objDict.Keys()
If objDict.Exists(item) Then LOG item & vbTab & objDict(item)
Next
HOLDstrIP = ""
objDict.RemoveAll
objDict(strIP) = 0
objDict(strUser) = 0
End Sub
'After the For loop is finished, I flush it out one last time by calling:
CountThemOut
感谢您的帮助@ Ekkehard.Horner !!非常感谢。
我写的日志文件看起来像这样:
xxx.xxx.xxx.xxx 25
username1 12
username2 15
username3 7
yyy.yyy.yyy.yyy 18
username1 10
username2 14
username3 20
: - )