2013-03-14 2 views
3

Есть ли способ использовать IEnumerableFor Each -Loop для синтаксического анализа нескольких определений в SortedDictionary? Я бы хотел использовать его в качестве простой структуры базы данных, я думаю. Например, скажем, мой словарь используется для вращения статьи и выглядит следующим образом. Для каждого слова в предложении (моя строка) я бы создал новую версию этой строки, используя синоним (мои определения). Это даже лучший вариант? Это то, что я до сих пор:Перестановочные множественные значения словаря с использованием C#

string testSentence = "Take it or beat it."; 

List<string> allSynonyms = SynonymUtility.AlternativesOf(testSentence).ToList(); 
variations.AddRange(allSynonyms); 


public class SynonymUtility 
{ 
    private static readonly SortedDictionary<char, string> synonymList = new SortedDictionary<char, string> 
    { 
     {'but', "however"}, 
     {'take', "abduct, abstract, accroach"}, 
     {'beat', "hit, lash, punch, shake"}, 
     {'end', " butt, confine, cusp"}; 
    } 

    public static IEnumerable<string> AlternativesOf(string arg) 
    { 
     arg = arg.ToLower(); 
     string[] words = arg.Split(" ")); 
     //END HERE I AM STUCK... 
    }  

Так как вы можете видеть, я на моем пути к решению, но я не могу понять, как взять каждого из расщепленных слов и заменить их каждый синонимов в словаре. Каждая попытка заменит только один элемент ... так что в конце будет 9 перестановок строки предложения.

В любом случае, любая помощь будет оценена по достоинству.

+0

Почему не просто иметь список как словарь значение? –

+0

Как вы это сделаете? Разве не требуется отдельный список для каждого слова? – Jeagr

+1

Нет, вы можете сделать 'Словарь <строка, список > myDictionary = новый словарь <строка, список >;' Затем вы можете добавить список в словарь или добавить новый синоним существующего списка, подобный этому 'myDictionary [" beat "] .Add (" hit ");' –

ответ

3

Это решает проблему:

Я измененную структуру из вас синоним словаря, так что значения Списки:

private static readonly SortedDictionary<string, List<string>> synonymList 
      = new SortedDictionary<string, List<string>> 
      { 
       {"but", new List<string> { "however" }}, 
       {"take", new List<string> { "abduct", "abstract", "accroach"}}, 
       {"beat", new List<string> {"hit", "lash", "punch", "shake"}}, 
       {"end", new List<string> {"butt", "confine", "cusp"}} 
      }; 

Функция для вывода всех альтернативных предложений:

public static IEnumerable<string> AlternativesOf(string arg) 
    { 
     //First of all, build up a 2d array of all your options 
     var words = arg.Split(' ').Select(w=> w.ToLower()).ToList(); 
     var options = new List<List<string>>(); 

     foreach (var word in words) 
     { 
      if (synonymList.ContainsKey(word)) 
      { 
       //Add the original word to the list of synonyms 
       options.Add(synonymList[word] 
           .Concat(new List<string> { word }).ToList()); 
      } 
      else 
      { 
       //Just use the original word only 
       options.Add(new List<string> { word }); 
      } 
     } 

     //Now return all permutations of the 2d options array 
     return AllPermutationsOf("", options, 0); 
    } 

Функция для получения всех перестановок:

public static IEnumerable<string> AllPermutationsOf 
      (string sentence, List<List<string>> options, int count) 
    { 
     if (count == options.Count) 
     { 
      yield return sentence; 
     } 
     else 
     { 
      foreach (string option in options[count]) 
      { 
       foreach (var childOption in AllPermutationsOf 
          (sentence + " " + option, options, count + 1)) 
       { 
        yield return childOption; 
       } 
      } 
     } 
    } 
Использование

Примера:

string testSentence = "Take it or beat it."; 
var alternatives = AlternativesOf(testSentence).ToList(); 

     /* Output: 

      abduct it or hit it. 
      abduct it or lash it. 
      abduct it or punch it. 
      abduct it or shake it. 
      abduct it or beat it. 
      abstract it or hit it. 
      abstract it or lash it. 
      abstract it or punch it. 
      abstract it or shake it. 
      abstract it or beat it. 
      accroach it or hit it. 
      accroach it or lash it. 
      accroach it or punch it. 
      accroach it or shake it. 
      accroach it or beat it. 
      take it or hit it. 
      take it or lash it. 
      take it or punch it. 
      take it or shake it. 
      take it or beat it. */ 
+0

Отлично! Хотя я просто искал некоторых указателей, я ценю помощь. Еще раз спасибо! – Jeagr

Смежные вопросы