计算txt文件vb.net中的特定单词数

计算txt文件vb.net中的特定单词数,vb.net,word-count,Vb.net,Word Count,如何使用vb.net计算特定文本文件中的特定单词数假定为4.0 单词必须完全匹配(不包括大小写混合)。如果要计算匹配的子单词,例如搜索“sub”并将“subway”计算为单词,请更改为LCase(strWord).Contains(LCase(“TargetWord”) 类似这样的东西可以帮助您: Private Function GetWordCountInFile(ByVal filepath As String, ByVal word As String) Dim dict As

如何使用vb.net计算特定文本文件中的特定单词数假定为4.0

单词必须完全匹配(不包括大小写混合)。如果要计算匹配的子单词,例如搜索“sub”并将“subway”计算为单词,请更改为LCase(strWord).Contains(LCase(“TargetWord”)


类似这样的东西可以帮助您:

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
或者类似的:(不需要声明额外的变量来保存字数)


将其加载到字符串变量中,然后执行以下操作:与
“\b查找我\b”
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