我正在尝试阅读文本文件并计算文本文件中出现短语/字符串(不是单词)的次数,但到目前为止我所拥有的是:
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("D:\VBscript project\testing.txt", ForReading)
strContents = objFile.ReadAll
objFile.Close
i = 0
arrLines = Split(strContents, "")
For Each strLine in arrLines
If InStr(strLine, "hi there") Then
i = i + 1
End If
Next
WScript.Echo "Number of times word occurs: " & i
Run Code Online (Sandbox Code Playgroud)
这只会让我计算一个单词出现的次数,当我尝试调整它来计算短语时,这不起作用。
考虑下面的例子:
strPath = "D:\VBscript project\testing.txt"
strPhrase = "hi there"
strContent = ReadTextFile(strPath, 0)
arrContent = Split(strContent, strPhrase)
MsgBox "Number of times phrase occurs: " & UBound(arrContent)
Function ReadTextFile(strPath, lngFormat)
' lngFormat -2 - System default, -1 - Unicode, 0 - ASCII
With CreateObject("Scripting.FileSystemObject").OpenTextFile(strPath, 1, False, lngFormat)
ReadTextFile = ""
If Not .AtEndOfStream Then ReadTextFile = .ReadAll
.Close
End With
End Function
Run Code Online (Sandbox Code Playgroud)
请注意,Split-based 方法区分大小写。