#vb.net
#vb.net
Вопрос:
Я создаю поисковую систему в vb.net который должен был бы искать слово, введенное пользователем, в 40 текстовых файлах в каталоге проекта.
Он должен возвращать результаты в виде общего количества совпадений (текстовых файлов) и количества раз, когда это слово встречается в каждом файле. Любые предложения для начала были бы благодарны.
С уважением.
Ответ №1:
получите список файлов в каталоге с помощью чего-то вроде: 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()
Ответ №2:
Попробуйте этот код в консольном приложении, чтобы не только найти слово, но и получить результаты, используя регулярное выражение.
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:" amp; 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