too*_*oop 15 vbscript scripting
需要一个接受文件名作为参数的函数,然后返回该文件中的行数.
应该在30秒内获取一个1000万行文件的计数.
目前有一些东西 - 但它与大文件太慢:
Dim objFSO, strTextFile, strData, arrLines, LineCount
CONST ForReading = 1
'name of the text file
strTextFile = "sample.txt"
'Create a File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Open the text file - strData now contains the whole file
strData = objFSO.OpenTextFile(strTextFile,ForReading).ReadAll
'Split by lines, put into an array
arrLines = Split(strData,vbCrLf)
'Use UBound to count the lines
LineCount = UBound(arrLines) + 1
wscript.echo LineCount
'Cleanup
Set objFSO = Nothing
Run Code Online (Sandbox Code Playgroud)
小智 21
如果有人仍在寻找更快的方法,这里是代码:
Set fso = CreateObject("Scripting.FileSystemObject")
Set theFile = fso.OpenTextFile("C:\textfile.txt", 8, True)
WScript.Echo theFile.Line
Set Fso = Nothing
Run Code Online (Sandbox Code Playgroud)
当然,处理时间很大程度上取决于文件大小,而不仅仅取决于行号.与RegEx方法相比,TextStream.Line属性至少快3倍.
我看到的唯一选择是逐行读取行(编辑:或者甚至只是逐个跳过它们),而不是一次读取整个文件.不幸的是我无法测试哪个更快.我想跳绳更快.
Dim objFSO, txsInput, strTemp, arrLines
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
strTextFile = "sample.txt"
txsInput = objFSO.OpenTextFile(strTextFile, ForReading)
'Skip lines one by one
Do While txsInput.AtEndOfStream <> True
txsInput.SkipLine ' or strTemp = txsInput.ReadLine
Loop
wscript.echo txsInput.Line-1 ' Returns the number of lines
'Cleanup
Set objFSO = Nothing
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我冒昧地删除了你的一些'comments.在良好实践方面,它们是多余的,并没有真正增加任何解释价值,特别是当它们基本上重复了方法名称时,例如
'Create a File System Object
... CreateObject("Scripting.FileSystemObject")
Run Code Online (Sandbox Code Playgroud)
文件太大......
以下是我所知道的最有效的方法:
Dim oFso, oReg, sData, lCount
Const ForReading = 1, sPath = "C:\file.txt"
Set oReg = New RegExp
Set oFso = CreateObject("Scripting.FileSystemObject")
sData = oFso.OpenTextFile(sPath, ForReading).ReadAll
With oReg
.Global = True
.Pattern = "\r\n" 'vbCrLf
'.Pattern = "\n" ' vbLf, Unix style line-endings
lCount = .Execute(sData).Count + 1
End With
WScript.Echo lCount
Set oFso = Nothing
Set oReg = Nothing
Run Code Online (Sandbox Code Playgroud)