2011-11-02 147 views
0

我在vb.net中構建了一個搜索引擎,它必須搜索用戶在項目目錄中的40個文本文件中輸入的單詞。vb.net中的搜索引擎

它應該返回結果作爲匹配的總數(文本文件)和這個單詞在每個文件中的次數。任何啓動建議將不勝感激。

問候。

回答

0

獲得該目錄中的文件列表的東西,如:Directory.GetFiles(ProjectDir, "*.*"),然後閱讀列表這樣每個文件:

 Dim sr As StreamReader = New StreamReader(fileName) 
     Dim line As String 
     Do 
      line = sr.ReadLine() 
      scan the line and count 
     Loop Until line Is Nothing 
     sr.Close() 
0

試試這個代碼,在控制檯應用程序,不僅能找到一個word 即使您可以使用RegEx表達式來獲得結果。

Class TextFileInfo 
Public File As System.IO.FileInfo 
public Count As Integer 
public FileText As String 
public ItMatch as Boolean = False 

Sub New (FileFullName as String,WordPattern as String) 
     File = new System.IO.FileInfo(FileFullName) 

     Using Fs As System.IO.StreamReader(File.FullName) 
      FileText = Fs.ReadToEnd()'//===>Read Text  
     End Using 
     Count = _CountWords(WordPattern,FileText) 
     ItMatch = Count > 0 
End Sub 

Public Sub DisplayInfo() 
    System.Console.WriteLine("File Name:" + File.Name) 
    System.Console.WriteLine("Matched Times:" & Count) 
End Sub 

Private Function _CountWords(Word As String,Text As String) as Integer 
    Dim RegEx as System.Text.RegularExpressions.Regex(Word) 
    return RegEx.Matches(Text).Count'//===>Returns how many times this word match in the Text 
End Fuction 
End Class 

Public Function SearchEngine(PatternWord As String,RootDirectory As String) List(Of TextFileInfo) 
    Dim MatchedFiles As New List(Of TextFileInfo) 
    Dim RootDir As New System.IO.DirectoryInfo(RootDirectory) 

    For Each iTextFile as System.IO.FileInfo In RootDir.GetFiles("*.txt") 
      '//===>Create a object of TextFileInfo and check if the file contains the word 
      Dim iMatchFile as New TextFileInfo(iTextFiles.FullName,PatternWord) 

      If iMatchFile.ItMatch Then 
       '//===>Add the object to the list if it has been matches 
       MatchedFiles.Add(iMatchFile) 
      End If 
    Loop 

    retur MatchedFiles '//===>Return the results of the files that has the matched word 
End Function 

Sub Main() 
    Dim SearchResults as List(Of TextFileInfo) = SearchEngine("JajajaWord","C:\TextFiles\") 

     For Each iSearch As TextFileInfo In SearchResults 
     iSearch.DisplayInfo() 
     Loop 

End Sub