Imports System
Imports System.Net
Imports System.Text.RegularExpressions
Imports System.Collections.Generic
Class DictionarySortByValue
Shared Sub makeDict(ByVal dict As Dictionary(Of String, Integer))
Dim html As String
' HTMLの取得
Using wc As New WebClient()
html = wc.DownloadString("http://www.atmarkit.co.jp/")
End Using
' 単語に分割して、各単語の出現頻度をカウント
For Each s As String In Regex.Split(html, "\W")
Dim word As String = s.Trim()
If Not word = "" Then
If dict.ContainsKey(word) Then
dict(word) += 1
Else
dict(word) = 1
End If
End If
Next
End Sub
Shared Sub Main()
Dim dict As New Dictionary(Of String, Integer)
makeDict(dict)
Dim sorted As List(Of KeyValuePair(Of String, Integer)) = sortByValue(dict)
' sorted.Reverse() ' 逆順にする場合
For Each kvp As KeyValuePair(Of String, Integer) In sorted
Console.WriteLine(kvp.Key & ":" & kvp.Value)
Next
' 出力例:
' a:542
' td:394
' 0:328
' width:289
' tr:284
' ……
End Sub
Shared Function hikaku( _
ByVal kvp1 As KeyValuePair(Of String, Integer), _
ByVal kvp2 As KeyValuePair(Of String, Integer)) As Integer
' Valueの大きい順にソート
Return kvp2.Value - kvp1.Value
End Function
Shared Function sortByValue( _
ByVal dict As Dictionary(Of String, Integer)) _
As List(Of KeyValuePair(Of String, Integer))
Dim list As New List(Of KeyValuePair(Of String, Integer))(dict)
list.Sort(AddressOf hikaku)
Return list
End Function
End Class
Shared Function hikaku(Of TKey, TValue As IComparable(Of TValue))( _
ByVal kvp1 As KeyValuePair(Of TKey, TValue), _
ByVal kvp2 As KeyValuePair(Of TKey, TValue)) As Integer
Return kvp2.Value.CompareTo(kvp1.Value)
End Function
Shared Function sortByValue(Of TKey, TValue As IComparable(Of TValue))( _
ByVal dict As Dictionary(Of TKey, TValue)) _
As List(Of KeyValuePair(Of TKey, TValue))
Dim list As New List(Of KeyValuePair(Of TKey, TValue))(dict)
' Valueの大きい順にソート
list.Sort(AddressOf hikaku)
Return list
End Function