如何修改VB.NET代码实现同时统计文本中多个指定单词的出现次数
VB.NET多关键词词频统计修改方案
修改思路
- 将原单个搜索词变量替换为字符串数组,存储所有待检索的关键词
- 提前将所有搜索词统一转为小写格式存入集合,避免重复转换提升匹配效率
- 修改LINQ查询的匹配逻辑,支持判断当前单词是否属于目标搜索词集合
- 新增分组统计逻辑,可直接输出每个关键词的出现次数,也可按需统计所有关键词的总出现次数
修改后完整代码
Class CountWords Shared Sub Main() Dim text As String = "Historically, the world of data and the world of objects" & " have not been well integrated. Programmers work in C# or Visual Basic" & " and also in SQL or XQuery. On the one side are concepts such as classes," & " objects, fields, inheritance, and .NET Framework APIs. On the other side" & " are tables, columns, rows, nodes, and separate languages for dealing with" & " them. Data types often require translation between the two worlds; there are" & " different standard functions. Because the object world has no notion of query, a" & " query can only be represented as a string without compile-time type checking or" & " IntelliSense support in the IDE. Transferring data from SQL tables or XML trees to" & " objects in memory is often tedious and error-prone." ' 替换为多关键词数组,可自行增减需要搜索的词 Dim searchTerms As String() = {"data", "separate", "node"} ' 提前转小写生成匹配集合,避免查询时重复转换提升效率 Dim lowerSearchTerms = searchTerms.Select(Function(t) t.ToLowerInvariant()).ToList() ' 文本拆分逻辑保持不变 Dim dataSource As String() = text.Split(New Char() {" ", ",", ".", ";", ":"}, StringSplitOptions.RemoveEmptyEntries) ' 统计每个关键词的独立出现次数 Dim countQuery = From word In dataSource Let lowerWord = word.ToLowerInvariant() Where lowerSearchTerms.Contains(lowerWord) Group By key = lowerWord Into Group Select New With { .Term = searchTerms.First(Function(t) t.ToLowerInvariant() = key), .Count = Group.Count() } ' 输出每个关键词的统计结果 For Each item In countQuery Console.WriteLine($"{item.Count} occurrence(s) of the search term ""{item.Term}"" were found.") Next ' 若仅需要所有关键词的总出现次数,可替换上面的统计和输出逻辑为以下代码 ' Dim totalCount As Integer = dataSource.Count(Function(word) lowerSearchTerms.Contains(word.ToLowerInvariant())) ' Console.WriteLine($"Total {totalCount} occurrence(s) of all search terms were found.") ' 保持控制台窗口开启逻辑不变 Console.WriteLine("Press any key to exit.") Console.ReadKey() End Sub End Class
运行输出示例
3 occurrence(s) of the search term "data" were found. 1 occurrence(s) of the search term "node" were found. 1 occurrence(s) of the search term "separate" were found. Press any key to exit.
内容的提问来源于stack exchange,提问作者Timi
相关产品推荐
相关产品推荐

