這個現在應該讓你關閉,在C#:
class Program
{
public class Node
{
private string _term;
private Dictionary<string, KeyValuePair<Node, Node>> _related = new Dictionary<string, KeyValuePair<Node, Node>>();
public Node(string term)
{
_term = term;
}
public void Add(string phrase, Node previous, string [] phraseRemainder, Dictionary<string,Node> existing)
{
Node next= null;
if (phraseRemainder.Length > 0)
{
if (!existing.TryGetValue(phraseRemainder[0], out next))
{
existing[phraseRemainder[0]] = next = new Node(phraseRemainder[0]);
}
next.Add(phrase, this, phraseRemainder.Skip(1).ToArray(), existing);
}
_related.Add(phrase, new KeyValuePair<Node, Node>(previous, next));
}
}
static void Main(string[] args)
{
string [] sentences =
new string [] {
"The beautiful sky",
"Beautiful sky dream",
"beautiful dream"
};
Dictionary<string, Node> parsedSentences = new Dictionary<string,Node>();
foreach(string sentence in sentences)
{
string [] words = sentence.ToLowerInvariant().Split(' ');
Node startNode;
if (!parsedSentences.TryGetValue(words[0],out startNode))
{
parsedSentences[words[0]] = startNode = new Node(words[0]);
}
if (words.Length > 1)
startNode.Add(sentence,null,words.Skip(1).ToArray(),parsedSentences);
}
}
}
我把假設你想保留的實際初始短語的自由。最後,你會在短語中列出單詞列表,並在每個短語列表中使用該單詞的短語列表,以及每個短語中下一個和前一個單詞的引用。
使用關聯數組可以讓您快速解析Perl中的句子。它比你預期的要快得多,並且可以像結構樹那樣有效地排出,以供後續的高級語言使用。你想要一個算法。 – ojblass 2009-04-08 06:24:03
@LukasŠalkauskas,你爲什麼要刪除這個問題?這很棒。圖表中只有一個錯字。 – 2009-04-09 06:50:51