用于计算文本文件中行数的函数

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倍.

  • 您可能希望最后关闭该文件,"Set oFso = Nothing"应为"Set fso = Nothing".我还要指出8表示"For appending",这就是它立即读到文件末尾的原因. (4认同)
  • 并使用theFile.Line-1返回文件中存在的行数,因为theFile.Line返回您将要写入但尚不存在的行数。 (3认同)
  • 另外,我会将最后一个参数设置为False,因此如果文件不存在则不创建文件,而是允许其出错。 (2认同)

Jea*_*ett 7

我看到的唯一选择是逐行读取行(编辑:或者甚至只是逐个跳过它们),而不是一次读取整个文件.不幸的是我无法测试哪个更快.我想跳绳更快.

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)

  • +1我本人将要发布此帖子,发现它的速度快了一倍(5秒钟内有1000000行)。作为一种优化,您可以在循环“ filInput.ReadLine”中创建唯一的东西,然后在完成后,“ filInput.Line-1”将成为行数(因此避免使用counter和buffer变量) (2认同)

Kul*_*gin 7

文件太大......
以下是我所知道的最有效的方法:

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)