2013-03-09 60 views
0

我正在處理用戶提供一組單詞(通常少於10)的C#應用​​程序,並且我需要檢索這些單詞的所有同義詞。這是我第一次使用字典和這些東西。我需要知道要遵循的步驟,以及是否存在提供同義詞的現有字典,以便與我的應用程序集成,或者是否存在可以使用的開放源代碼應用程序或代碼。如何執行查詢擴展

+0

你有字典可以使用嗎?它是否必須是本地字典,或者是否允許使用API​​? – 2013-03-09 17:30:49

+0

谷歌搜索「字典API」返回結果很多..在這裏其中之一:http://www.dictionaryapi.com/ – Fredrik 2013-03-09 17:36:06

+0

親愛的TheGreatCO,我沒有一本字典可以使用,字典應該是本地和我不需要一個字典,我需要一種同義詞來提供給定單詞的同義詞,某​​種查詢擴展。親愛的FredrickRedin我做了一些研究,所有我找到的都是API,我不需要它。 – user1905455 2013-03-10 22:16:47

回答

1

回答你的第一個問題。你可以在這裏找到一個詞庫下載:http://wordpresscloaker.com/blog/download-free-english-thesaurus-format-txt.html

我不作任何承諾,質量,準確性,合法性,該文件的許可使用,或完整性。不過,這會讓你走上正軌。您需要提取mthesaur.txt並將其添加到您的項目文件夾。

接下來,你需要做以下的文本文件閱讀:

var reader = new StreamReader(File.OpenRead(@"C:\mthesaur.txt")); 
var dict = new Dictionary<string, string>(); 
while (!reader.EndOfStream) 
{ 
    // Read the file line by line. 
    var line = reader.ReadLine(); 

    // If the line isn't null, we can use it. This shouldn't happen but it is a good sanity check. 
    if (line == null) continue; 
    // Split the line by the delimiter (a comma) so we can get the main word, the first one on the line. 
    var splitLine = line.Split(','); 
    var mainWord = splitLine[0]; 
    // To save us from having to loop through and only get the indexes above 0 (eg, skip the main word) we will just simply remove it from the line so we have just synonyms. 
    line = line.Replace(mainWord + ",", string.Empty); 
    // Now we make use of the dictionary type in C# and add the mainword as the key and the synonyms as the value. 
    try 
    { 
     dict.Add(mainWord, line); 
    } 
    catch (ArgumentException argEx) 
    { 
     Console.WriteLine("Attempted to add {0} to the dictionary but it already exists.", mainWord); 
    } 
} 

現在,我們已經在C#中的鍵/值字典的一切,你可以使用LINQ查詢出來的同義詞一個輸入的單詞。這可以通過使用包含詞典中所有鍵值的下拉列表(不推薦,因爲這將是一個非常大的下拉列表,並且很難爲用戶導航),ListBox(更好,更容易導航),或純文本搜索框。雖然這並不能完全回答你的問題,因爲這裏沒有任何關於爲用戶處理GUI的內容,這應該會讓你順利地完成任務。

+0

我已經試過你的代碼,但是當我編譯它時,我在最後一行得到一個ArgumentException,並且它說「具有相同密鑰的項目已被添加。」任何想法出了什麼問題? – user1905455 2013-03-12 09:28:34

+0

@ user1905455我更新了答案,以便在不使程序崩潰的情況下捕獲此異常。不過,我建議你在'Console.WriteLine'上放置一個斷點,以查看哪些鍵特別會導致問題。然後,我建議您檢查實際的同義詞庫文件,看看這是編程錯誤還是代碼問題。 – 2013-03-12 14:00:49

+0

謝謝你這個代碼工作得很好,我發現了重複的關鍵 – user1905455 2013-03-12 18:01:37

0

如果您使用SQL full text search或底層技術 - 微軟搜索服務器(有一個免費的Express SKU),你會發現多種語言和其他自然語言處理工具的同義詞庫。當然,我假設你工作的一個實際的項目,不做作業......

如果你是更進開源的,看看Lucene.net - 它提供了一個搜索引擎,我敢肯定它有thesaur