大家好, 我有一个代码来从解析结果中获取句子的第一个名词。我写了以下代码。但似乎有些问题。如果语句没有中断for循环。任何人都可以帮我解决一下吗?
提前致谢。
public static String Find_Noun(Parse p)
{
label:
for(Parse k:p.getChildren())
{
if((k.getType()).equals("NN")||(k.getType()).equals("NNP")||
(k.getType()).equals("NNS")||(k.getType()).equals("NNPS"))
{
noun=k.toString();
System.out.println(noun);
break label; // I am aware that label is not needed,
// but it doesn't work either way.
}
else
{
System.out.println("else "+k);
Find_Noun(k);
}
}
return noun;
}
输入:
成为\ VBD a \ DT常规\ JJ客户\ NN of \ IN \ \ _ \ n \ n \ n郊区\ JJ花园\ NN
输出结果为:
else became
else became
else a regular customer of a suburban garden
else a regular customer
else a
else a
else regular
else regular
customer \\This is the string to be extracted
else of a suburban garden
else of
else of
else a suburban garden
else a
else a
else suburban
else suburban
garden
garden
答案 0 :(得分:4)
问题在于您在每个非名词上递归调用Find_Noun
。所以是的,它 突破了你正在寻找的一次迭代的循环......但是它只是回到了堆栈的前一级。 / p>
我不清楚为什么你会再次递归,但如果你真的做需要递归,你需要一些方法来检测是否真的发现了递归调用是否是名词,如果是,则立即返回。所以可能是这样的:
// Renamed method to follow Java naming conventions
public static String findNoun(Parse p)
{
for(Parse k : p.getChildren())
{
// Removed a bunch of extraneous brackets, and added whitespace
// for readability. You should consider a set NOUN_TYPES
// so you could use if (NOUN_TYPES.contains(k.getType()) instead.
if (k.getType().equals("NN") || k.getType().equals("NNP") ||
k.getType().equals("NNS")|| k.getType().equals("NNPS"))
{
return k.toString();
}
else
{
String possibleNoun = findNoun(k);
// Return immediately if the recursion found a noun
if (possibleNoun != null)
{
return possibleNoun;
}
}
}
// Nothing found in this node or children: tell the caller
return null;
}