Skip to content

Instantly share code, notes, and snippets.

@pjmagee
Created October 10, 2012 17:46
Show Gist options
  • Select an option

  • Save pjmagee/3867181 to your computer and use it in GitHub Desktop.

Select an option

Save pjmagee/3867181 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.IO;
using DocSearch.Util;
namespace DocSearch.Query.Impl
{
public class QueryInterpreter : IQueryInterpreter
{
private IEnumerable<string> _terms;
private readonly List<FileInfo> _textFiles;
public QueryInterpreter(TextFileManager fileManager)
{
if(fileManager == null)
throw new ArgumentNullException("fileManager");
_textFiles = fileManager.TextFiles;
}
public QueryResponse Query(string query)
{
_terms = query.Split(new[] { " and " }, StringSplitOptions.None);
List<ResultSet> resultSets = new List<ResultSet>();
QueryResponse response = new QueryResponse(resultSets);
foreach(var file in _textFiles)
{
// Which file is this
int currentFile = 1;
// What is the file name
TextReader reader = new StreamReader(file.FullName);
// Split the file contents into sentences
IEnumerable<string> sentences = reader.ReadToEnd().Split(new[]{ ". " }, StringSplitOptions.None);
// For each term in the _terms need finding
// First we search apple
// Then we search banana
foreach (string term in _terms)
{
ResultSet resultSet = new ResultSet();
resultSet.TextFile = file.FullName;
resultSet.Term = term;
// We are searching each sentence individually for the word apple
int currentSentence = 1; // This increments per sentence only
int currentPosition = 0; // This always increments from 0 to the last increment of a word in a collection of strings
foreach (string sentence in sentences)
{
foreach(string word in sentence.Split(new string[] { " " }, StringSplitOptions.None))
{
// if apple == apple found in sentence
if (Sanitize(word) == term)
{
// MATCH 1
resultSet.SentencePosition.Add(currentPosition, currentSentence);
}
currentPosition++;
}
currentSentence++;
}
// Add this terms resultSet information
response.ResultSets.Add(resultSet);
}
// Each term search has been copleted
}
// return the response container
return response;
}
private string Sanitize(string s)
{
// This function will need tweaking
return s.Replace(",", "");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment