Hie guys.How do you write a vb function that returns the frequency of each word that appears in a given text file.e.g.if the word "the" appears twice,it would return "The word 'the' appears 2 times".This has to be done until the end of the file without searching for a particular word.

Recommended Answers

All 5 Replies

Hi Schimusi,

Have you tried it yourself first?
First show your effort here, or any part where you are having problem.

commented: I agree. +3

Stick them in a dictionary and do what you need to do from there. If you take advantage of a case insensitive dictionary and using Regex to split on word boundaries you can also eliminate punctuation errors in your application.

Public Class FormStart

	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

		Dim sentence As String = "the quick brown fox jumped over a lazy dog in the brown yard with elvis sitting by his brown horse"
		Dim words() As String = System.Text.RegularExpressions.Regex.Split(sentence, "\W+")
		Dim dict As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)
		For Each word In words
			Dim cnt As Integer
			If (dict.TryGetValue(word, cnt)) Then
				dict(word) = cnt + 1
			Else
				dict.Add(word, 1)
			End If
		Next

		For Each key In dict
			Console.WriteLine("Word: {0} Count:{1}", key.Key, key.Value)
		Next
		Debugger.Break()
	End Sub
End Class

Stick them in a dictionary and do what you need to do from there. If you take advantage of a case insensitive dictionary and using Regex to split on word boundaries you can also eliminate punctuation errors in your application.

Public Class FormStart

	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

		Dim sentence As String = "the quick brown fox jumped over a lazy dog in the brown yard with elvis sitting by his brown horse"
		Dim words() As String = System.Text.RegularExpressions.Regex.Split(sentence, "\W+")
		Dim dict As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)
		For Each word In words
			Dim cnt As Integer
			If (dict.TryGetValue(word, cnt)) Then
				dict(word) = cnt + 1
			Else
				dict.Add(word, 1)
			End If
		Next

		For Each key In dict
			Console.WriteLine("Word: {0} Count:{1}", key.Key, key.Value)
		Next
		Debugger.Break()
	End Sub
End Class

Thank you sknake and all you guys.It is working.

Hi Schimusi,

Mark the Thread as Solved If you have got the solution... :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.