我有一个程序(C#),它生成了一个字符串列表(原始字符串的排列组合)。大多数字符串都是符合预期的原始字母的随机分组(例如etam,aemt,team)。我想以编程方式找到列表中的一个实际英语单词。我需要一个同义词词典/字典来查找和比较每个字符串。有人知道可用的资源吗?我在C#中使用VS2008。
我有一个程序(C#),它生成了一个字符串列表(原始字符串的排列组合)。大多数字符串都是符合预期的原始字母的随机分组(例如etam,aemt,team)。我想以编程方式找到列表中的一个实际英语单词。我需要一个同义词词典/字典来查找和比较每个字符串。有人知道可用的资源吗?我在C#中使用VS2008。
// Read words from file.
string [] words = ReadFromFile();
Dictionary<String, List<String>> permuteDict = new Dictionary<String, List<String>>(StringComparer.OrdinalIgnoreCase);
foreach (String word in words) {
String sortedWord = new String(word.ToArray().Sort());
if (!permuteDict.ContainsKey(sortedWord)) {
permuteDict[sortedWord] = new List<String>();
}
permuteDict[sortedWord].Add(word);
}
// To do a lookup you can just use
String sortedWordToLook = new String(wordToLook.ToArray().Sort());
List<String> outWords;
if (permuteDict.TryGetValue(sortedWordToLook, out outWords)) {
foreach (String outWord in outWords) {
Console.WriteLine(outWord);
}
}
你也可以使用维基词典。MediaWiki API(维基词典使用MediaWiki)允许你查询文章标题列表。在维基词典中,文章标题是字典中的词条之一。唯一的问题是,外语单词也包含在字典中,所以有时可能会得到“不正确”的匹配结果。当然,你的用户还需要互联网访问权限。你可以在以下链接获取API的帮助和信息:http://en.wiktionary.org/w/api.php
这是一个查询URL的示例:
http://en.wiktionary.org/w/api.php?action=query&format=xml&titles=dog|god|ogd|odg|gdo
这将返回以下xml:
<?xml version="1.0"?>
<api>
<query>
<pages>
<page ns="0" title="ogd" missing=""/>
<page ns="0" title="odg" missing=""/>
<page ns="0" title="gdo" missing=""/>
<page pageid="24" ns="0" title="dog"/>
<page pageid="5015" ns="0" title="god"/>
</pages>
</query>
</api>
public static IEnumerable<string> FilterRealWords(IEnumerable<string> testWords)
{
string baseUrl = "http://en.wiktionary.org/w/api.php?action=query&format=xml&titles=";
string queryUrl = baseUrl + string.Join("|", testWords.ToArray());
WebClient client = new WebClient();
client.Encoding = UnicodeEncoding.UTF8; // this is very important or the text will be junk
string rawXml = client.DownloadString(queryUrl);
TextReader reader = new StringReader(rawXml);
XPathDocument doc = new XPathDocument(reader);
XPathNavigator nav = doc.CreateNavigator();
XPathNodeIterator iter = nav.Select(@"//page");
List<string> realWords = new List<string>();
while (iter.MoveNext())
{
// if the pageid attribute has a value
// add the article title to the list.
if (!string.IsNullOrEmpty(iter.Current.GetAttribute("pageid", "")))
{
realWords.Add(iter.Current.GetAttribute("title", ""));
}
}
return realWords;
}
这样调用:
IEnumerable<string> input = new string[] { "dog", "god", "ogd", "odg", "gdo" };
IEnumerable<string> output = FilterRealWords(input);
我尝试使用LINQ to XML,但我对它不是很熟悉,所以这让我很头疼,最终放弃了。