0

vb.net を使用して特定のテキスト ファイル内の特定の単語をカウントするにはどうすればよいですか

4

2 に答える 2

0

このようなものがあなたを助けるでしょう:

Private Function GetWordCountInFile(ByVal filepath As String, ByVal word As String)
    Dim dict As New Dictionary(Of String, Integer)()
    Dim lst As New List(Of String)(IO.File.ReadAllText(filepath).Split(" "))

    For Each entry As String In lst
        If Not (dict.ContainsKey(entry.ToLower.Trim)) Then
            dict.Add(entry.ToLower.Trim, 1)
        Else
            dict(entry.ToLower.Trim) += 1
        End If
    Next
    lst.Clear()
    Return dict(word.ToLower.Trim)
End Function

次のように使用できます。

   Dim count As Integer = GetWordCountInFile("../../Sample.txt", "sample")

これは、テキスト ファイル「sample.txt」で単語「sample」を検索し、カウントを返します。

また、良いものではないかもしれませんが、単一行のアプローチは次のようになります。

Private Function GetWordCountInFile(ByVal filepath As String, ByVal word As String)
    Return System.Text.RegularExpressions.Regex.Matches(IO.File.ReadAllText(filepath), "(?i)\b(\s+)?" & word & "(\s+|\S{0})\b|^" & word & "\.?$|" & word & "[\.\,\;]").Count
End Function

または次のようなもの: (単語数を保持するために追加の変数を宣言する必要はありません)

   Private Function GetWordCountInFile(ByVal filepath As String, ByVal word As String)
    Dim lst As New List(Of String)(IO.File.ReadAllText(filepath).ToLower.Split(New Char() {" ", ",", ";", ".", ":"}))
    Return lst.FindAll(Function(c) c.Trim() = word.ToLower).Count()
   End Function
于 2012-10-23T11:44:36.700 に答える