【发布时间】:2013-04-18 22:10:05
【问题描述】:
我想使用 JAVA 将 JSON 树中的稀有词替换为 _RARE_。
我的稀有词列表包含
late
populate
convicts
所以对于下面的 JSON
["S", ["PP", ["ADP", "In"], ["NP", ["DET", "the"], ["NP", ["ADJ", "late"], ["NOUN", "1700<s"]]]], ["S", ["NP", ["ADJ", "British"], ["NOUN", "convicts"]], ["S", ["VP", ["VERB", "were"], ["VP", ["VERB", "used"], ["S+VP", ["PRT", "to"], ["VP", ["VERB", "populate"], ["WHNP", ["DET", "which"], ["NOUN", "colony"]]]]]], [".", "?"]]]]
我应该得到
["S", ["PP", ["ADP", "In"], ["NP", ["DET", "the"], ["NP", ["ADJ", "_RARE_"], ["NOUN", "1700<s"]]]], ["S", ["NP", ["ADJ", "British"], ["NOUN", "_RARE_"]], ["S", ["VP", ["VERB", "were"], ["VP", ["VERB", "used"], ["S+VP", ["PRT", "to"], ["VP", ["VERB", "populate"], ["WHNP", ["DET", "which"], ["NOUN", "colony"]]]]]], [".", "?"]]]]
注意方法
["ADJ","late"]
被替换为
["ADJ","_RARE_"]
到目前为止,我的代码如下:
我递归地遍历树,一旦找到稀有词,我就创建一个新的 JSON 数组并尝试用它替换现有树的节点。请参阅下面的// this Doesn't work,这就是我卡住的地方。树在此函数之外保持不变。
public static void traverseTreeAndReplaceWithRare(JsonArray tree){
//System.out.println(tree.getAsJsonArray());
for (int x = 0; x < tree.getAsJsonArray().size(); x++)
{
if(!tree.get(x).isJsonArray())
{
if(tree.size()==2)
{
//beware it will get here twice for same word
String word= tree.get(1).toString();
word=word.replaceAll("\"", ""); // removing double quotes
if(rareWords.contains(word))
{
JsonParser parser = new JsonParser();
//This works perfectly
System.out.println("Orig:"+tree);
JsonElement jsonElement = parser.parse("["+tree.get(0)+","+"_RARE_"+"]");
JsonArray newRareArray = jsonElement.getAsJsonArray();
//This works perfectly
System.out.println("New:"+newRareArray);
tree=newRareArray; // this Doesn't work
}
}
continue;
}
traverseTreeAndReplaceWithRare(tree.get(x).getAsJsonArray());
}
}
上面的调用代码,我用google的gson
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(strJSON);
JsonArray tree = jsonElement.getAsJsonArray();
【问题讨论】:
-
你为什么不做一个
strJSON.replaceAll("(late|populate|convicts)", "_RARE_") -
+1 当然,我将尝试这样做,它可能适用于大多数情况。但提出这个问题的主要动机是了解/学习如何操作这种树。
-
抱歉,replaceAll() 对我不起作用,因为我的稀有词列表长 3435,而且它最终从 [ “SQ”、“迟到”]
-
发生上述情况是因为有一个“S”。在我的稀有列表中.. 我刚刚通过所有 3435 个稀有词找到了。
标签: java json data-structures tree