【问题标题】:Count Items in file using VB使用VB计算文件中的项目
【发布时间】:2020-03-27 09:52:00
【问题描述】:

对 VBS 有点陌生。我正在尝试计算文件中的字段并拥有此代码。

Col()
Function Col()

Const FSpec = "C:\test.txt"
Const del = ","

  dim fs : Set fs = CreateObject("Scripting.FileSystemObject")
  dim f : Set f = fs.OpenTextFile(FSpec, 1)
  Dim L, C

  Do Until f.AtEndOfStream
   L = f.ReadLine()
   C = UBound(Split(L, del))
   C = C +1

   WScript.Echo "Items:", C

  Loop
  f.Close

End Function

但它有效,我不想计算“”中的分隔符。

这是文件内容:

1,"2,999",3

所以基本上,我现在得到 4 个项目,但我想得到 3 个。有点卡在这里。

【问题讨论】:

  • 优雅的解决方案是使用正则表达式。不过,考虑到您已经嵌入了逗号,这可能很快就会变得复杂。一个非常糟糕但快速的解决方案是计算报价的数量并为您计算的每 2 个报价减去 1。这假设您的数据中引用的任何值都包含逗号!不漂亮,但很快。
  • 一种更繁琐的方法可能是在拆分之前逐个字符地解析每一行。如果遇到引号,请设置标志并继续下一个字符。如果是逗号,则删除,如果是引号引号,则重置标志,依此类推..
  • Richard L. Mueller 有一些关于如何Read CSV Files using VBScript 的体面示例 Richard 的第一个示例是上面 Arno van Boven 提出的第二个建议。其他替代方法包括使用 ADO、OLEDB 和/或 ODBC 文本驱动程序来解析 *.csv 文件。享受吧。
  • @ArnovanBoven 感谢您的建议。能够通过使用正则表达式来做到这一点。

标签: vbscript count scripting delimiter


【解决方案1】:

作为我的第二个建议的一个例子,一个非常简单的例子可能是这样的。不是说它是完美的,但它说明了这个想法:

Dim WeAreInsideQuotes  'global flag
Function RemoveQuotedCommas(ByVal line)
    Dim i
    Dim result
    Dim current
    For i = 1 To Len(line)
        current = Mid(line, i, 1) 'examine character
        'check if we encountered a quote
        If current = Chr(34) Then
            WeAreInsideQuotes = Not WeAreInsideQuotes 'toggle flag
        End If
        'process the character
        If Not (current = Chr(44) And WeAreInsideQuotes) Then 'skip if comma and insode quotes
            result = result & current
        End If
    Next
    RemoveQuotedCommas = result
End Function

【讨论】:

    猜你喜欢
    • 2013-01-20
    • 2021-11-15
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 2010-10-15
    • 1970-01-01
    相关资源
    最近更新 更多