计算vb.net中文本文件中特定单词的出现次数

问题描述 投票:1回答:4

我正在尝试计算文本文件中项目的数量,方法是计算项目早先在程序中输入的每个实例。

我已经从文件和文本框中读取了文本。问题是我当前的代码只是计算文本框中的字符数而不是我想要的单词在文件中的次数。

For Each desiredword As String In txtContentofFile.Text
        intdesiredword = intdesiredword + 1
        txtdesiredwordcount.Text = intdesiredword
Next

这会计算文本框中的字符数,而不是计算所需单词的数量。我在寻求帮助之前反复尝试并广泛搜索,但我只是不明白我的代码有什么问题。请帮忙 :)

vb.net word-count
4个回答
0
投票

你可以使用Split功能:

C#:

int count = txtContentofFile.Text.Split(desiredword).Length - 1;

VB.net:

Dim count As Integer = txtContentofFile.Text.Split(desiredword).Length - 1

0
投票

试试这个:

Dim text As String = IO.File.ReadAllText("C:\file.txt")
Dim wordsToSearch() As String = New String() {"Hello", "World", "foo"}
Dim words As New List(Of String)()
Dim findings As Dictionary(Of String, List(Of Integer))

'Dividing into words
words.AddRange(text.Split(New String() {" ", Environment.NewLine()}, StringSplitOptions.RemoveEmptyEntries))

findings = SearchWords(words, wordsToSearch)
Console.WriteLine("Number of 'foo': " & findings("foo").Count)

使用的功能:

Private Function SearchWords(ByVal allWords As List(Of String), ByVal wordsToSearch() As String) As Dictionary(Of String, List(Of Integer))
    Dim dResult As New Dictionary(Of String, List(Of Integer))()
    Dim i As Integer = 0

    For Each s As String In wordsToSearch
        dResult.Add(s, New List(Of Integer))

        While i >= 0 AndAlso i < allWords.Count
            i = allWords.IndexOf(s, i)
            If i >= 0 Then dResult(s).Add(i)
            i += 1
        End While
    Next

    Return dResult
End Function

您不仅会出现次数,还会有文件中的索引位置,可以轻松地在qazxsw poi中分组。


0
投票

在这种情况下,我更喜欢使用正则表达式。它们非常难以理解,但它们非常强大,并且通常比其他字符串操作技术更快。

Dictionary

在您的情况下,您正在寻找AllMatchResults.Count的值。

使用像Dim AllMatchResults As MatchCollection Try Dim RegexObj As New Regex(desiredword) AllMatchResults = RegexObj.Matches(txtContentofFile.Text) If AllMatchResults.Count > 0 Then ' Access individual matches using AllMatchResults.Item[] Else ' Match attempt failed End If Catch ex As ArgumentException 'Syntax error in the regular expression End Try 这样的优秀正则表达式工具来构建和测试表达式也是一个很好的帮助。 (上面的代码片段是由RegexBuddy生成的!)


-1
投票

请尝试以下代码

RegexBuddy
© www.soinside.com 2019 - 2024. All rights reserved.