1

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

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

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

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

4

4 回答 4

1

您可以使用拆分功能:

C#:

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

VB.net:

Dim count As Integer = txtContentofFile.Text.Split(desiredword).Length - 1
于 2013-03-20T13:05:31.530 回答
0

I prefer to use Regular Expressions in this type of situation. They are very tricky to understand but they are extremely powerful and typically faster than other string manipulation techniques.

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

In your case you are looking for the value from AllMatchResults.Count.

Using a great Regular Expression tool like RegexBuddy to build and test the expressions is a great help too. (The above code snippet was generated by RegexBuddy!)

于 2013-03-20T14:12:51.077 回答
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

您不仅会获得出现次数,还会获得文件中的索引位置,这些位置很容易分组在Dictionary.

于 2013-03-20T13:08:08.180 回答
-1

试试下面的代码

Function word_frequency(word_ As String, input As String) As Integer
    Dim ct = 0
    Try
        Dim wLEN = word_.Length
        Do While input.IndexOf(word_) <> -1
            Dim idx = input.IndexOf(word_) + wLEN
            ct += 1
            input = input.Substring(idx)
        Loop
    Catch ex As Exception

    End Try
    Return ct
End Function
于 2017-04-16T18:41:50.660 回答