Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Word search routine 1

Status
Not open for further replies.

susheel777

Programmer
Apr 28, 2003
17
0
0
SG
Hi.

I'm trying to write some code to do open a text file and count the number of occurences of each word in it. Any ideas?
 
thread222-666958
try checking out that tread as the guy had something the smae sort of prob as you
 
You can use the following code to do this job. As it makes use of the Dictionary object, you need to add a reference to Microsoft Scripting Runtime to run this program.
___
[tt]
Private Sub Form_Load()
Dim dic As Dictionary, N As Integer
Set dic = GetWordStats("C:\sample.txt")
'Print statistics in debug pane.
For N = 0 To dic.Count - 1
Debug.Print dic.Keys(N), dic.Items(N)
Next
Unload Me
End Sub

Function GetWordStats(FileName As String) As Dictionary
'Read the contents of the file.
Dim FileNum As Integer, S As String
FileNum = FreeFile
Open FileName For Binary Access Read As #FileNum
S = Space$(LOF(FileNum))
Get #FileNum, , S
Close #FileNum

'Remove ALL punctuation and paragraph marks
'which do not represent/make words
Dim N As Integer
For N = 1 To 127
Select Case Chr$(N)
Case "A" To "Z", "a" To "z", "0" To "9"
Case Else
S = Replace$(S, Chr$(N), " ")
End Select
Next

'Convert the string into array of words
Dim Words() As String
Words = Split(S)

'Now count occurence of each word individually
Dim WordStats As New Dictionary
Dim Word As Variant
WordStats.CompareMode = TextCompare
For Each Word In Words
If Len(Word) Then
'if word exists then
If WordStats.Exists(Word) Then
'increment the appearence count
WordStats(Word) = WordStats(Word) + 1
Else
'add a new word to the dictionary
WordStats.Add Word, 1
End If
End If
Next

'Return this dictionary
Set GetWordStats = WordStats
End Function
[/tt]
 
susheel777

If that post was helpful give Hypetia a star.

Andy
"Logic is invincible because in order to combat logic it is necessary to use logic." -- Pierre Boutroux
 
Very cool routine, Hypetia. I will stash that away in my trick bag! Enjoy a refreshing star!
Thanks,

Sam
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top