我正在从其他地方复制一个问题和答案,因为它部分地进入了我的需求,但不是完全。
在ASP经典中,有没有一种方法可以计算字符串在字符串数组中出现的次数并根据字符串和出现次数输出它们?
例如,如果我有一个包含以下内容的数组:
你好快乐你好你好测试你好测试快乐
输出为:
你好4快乐2测试1测试1
给出的答案是这样:
我假设语言是VBScript(因为大多数人在经典ASP中使用该语言。
您可以使用Dictionary对象来跟踪各个计数:
Function CountValues(pArray)
Dim i, item
Dim dictCounts
Set dictCounts = Server.CreateObject("Scripting.Dictionary")
For i = LBound(pArray) To UBound(pArray)
item = pArray(i)
If Not dictCounts.Exists(item) Then
dictCounts.Add item, 0
End If
dictCounts.Item(item) = dictCounts.Item(item) + 1
Next
Set CountValues = dictCounts
End Function
这很好,但是我无法弄清楚如何抓住最常用的2个单词,显示它们,然后将它们放在自己的变量中以供其他地方使用。
任何人都可以帮忙吗?
您可以使用this method遍历字典对象。在该循环内,跟踪一个新数组或两个新变量中前两个键及其计数。
您无法在VBScript中对Dictionary对象进行排序,因此您必须使用其他内容。
我的建议是使用断开连接的Recordset对象来保存项目及其出现。这种对象本身支持排序,并且非常易于使用。要实现此功能,请改用此类功能:
Function CountValues_Recordset(pArray)
Dim i, item
Dim oRS
Const adVarChar = 200
Const adInteger = 3
Set oRS = CreateObject("ADODB.Recordset")
oRS.Fields.Append "Item", adVarChar, 255
oRS.Fields.Append "Occurrences", adInteger, 255
oRS.Open
For i = LBound(pArray) To UBound(pArray)
item = pArray(i)
oRS.Filter = "Item='" & Replace(item, "'", "''") & "'"
If (oRS.EOF) Then
oRS.AddNew
oRS.Fields("Item").Value = item
oRS.Fields("Occurrences").Value = 1
Else
oRS.Fields("Occurrences").Value = oRS.Fields("Occurrences").Value + 1
End If
oRS.Update
oRS.Filter = ""
Next
oRS.Sort = "Occurrences DESC"
oRS.MoveFirst
Set CountValues_Recordset = oRS
End Function
并使用它来实现所需的输出:
Dim myArray, oRS
myArray = Array("happy", "hello", "hello", "testing", "hello", "test", "hello", "happy")
Set oRS = CountValues_Recordset(myArray)
Do Until oRS.EOF
Response.Write(oRS("item") & " " & oRS("Occurrences") & "<br />")
oRS.MoveNext
Loop
oRS.Close
Set oRS = Nothing
不要忘记在使用记录集后将其关闭并处置。
如果文本是这样的(“快乐你好你好测试你好测试你好”)
我该怎么办