2011-11-02 122 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