2012-10-23 119 views
0

如何在一個特定的文本文件尤斯vb.net計數特定單詞

+0

負載它變成一個字符串變量,然後執行此操作:http://stackoverflow.com/questions/9121907/count-words-in-visual-basic與'「\ bFind Me \ b」'結合' –

回答

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的」返回一個計數。

而且,可能不是一個很好的人,但單行的方法是:

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 
0

假設4.0計算特定的詞...

字必須是精確匹配(不含混合情況)。如果你想數匹配的子詞,如搜索「亞健康」和計數「地鐵」作爲一個詞,改變LCASE(strWord)。載有(LCASE(「TargetWord」))...

Dim intCount As Integer = 0 
    IO.File.ReadAllText("C:\file.txt").Split(" ").ToList().ForEach(Sub(strWord As String) 
                     If LCase(strWord) = LCase("TargetWord") Then 
                      intCount += 1 
                     End If 
                    End Sub) 
    MsgBox(CStr(intCount))