【问题标题】:VBScript - Generate a file with x lines of random textVBScript - 生成带有 x 行随机文本的文件
【发布时间】:2015-05-08 14:07:28
【问题描述】:

生成指定行数的文件需要什么代码。

即。有一些变量叫做 num_lines = 8743 然后为每一行生成一个长度在 200 到 300 个字符之间的随机字符串。

将此保存到文件中。

要随机化的代码开始:

For x=200 To 300
    Randomize
    vChar = Int(89*Rnd) + 33
    Rndz = Rndz & Chr(vChar)
  Next

【问题讨论】:

标签: scripting vbscript


【解决方案1】:

您可以使用第一个函数来创建随机字符串:

Function RandomString( ByVal strLen )
    Dim str
    Const LETTERS = "abcdefghijklmnopqrstuvwxyz0123456789"
    Randomize
    For i = 1 to strLen
        str = str & Mid( LETTERS, Int(strLen*Rnd+1) )
    Next
    RandomString = str
End Function

Source

然后感谢Scripting.FileSystemObject将其写入文件:

Const ForAppending = 8
Const max = 300
Const min = 200
Dim i As integer, lLines As Long
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
    ("c:\scripts\service_status.txt", ForAppending, True)
Randomize
For i = 1 To num_lines
   lLines = Int((max-min+1)*Rnd+min) 
   objTextFile.WriteLine(RandomString(lLines))
Next
objTextFile.Close

Source

【讨论】:

  • Randomize 不能在生成随机数的循环中调用,因为它会初始化生成器。
  • @]Ekkehard.Horner:更正了我的代码,谢谢。我误解了函数的工作原理
  • 我喜欢Const LETTERS 混淆数字的方式。
  • RandomNumber 函数是什么?
  • @Jean-François Corbett:该死!这是一个错字(老实说,我无法测试我的代码——我的错)。我会将我的代码更正为正确的内容
【解决方案2】:

这是答案中RandomString 函数的修复:

Function RandomString( ByVal strLen )
    Dim str, min, max

    Const LETTERS = "abcdefghijklmnopqrstuvwxyz0123456789"
    min = 1
    max = Len(LETTERS)

    Randomize
    For i = 1 to strLen
        str = str & Mid( LETTERS, Int((max-min+1)*Rnd+min), 1 )
    Next
    RandomString = str
End Function

另一个函数被破坏并且错误地从盐字符串中获取随机字符。此函数将返回一个包含字母和/或数字的随机字符串。

【讨论】:

  • 不能在生成随机数的循环中调用Randomize,因为它会初始化生成器
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-01
  • 1970-01-01
  • 2012-11-12
  • 1970-01-01
  • 2016-01-12
  • 2018-11-11
  • 1970-01-01
相关资源
最近更新 更多