使用哈希映射用名词替换数字

时间:2013-04-25 11:33:16

标签: java hashmap

我的输入句子是:

  

ram你在哪里

之后我会得到这个解析树:

' 2|TYPE|nx0e-VPadjn-Vnx1 1|RPron|nx-RP-S 0|NOUN|NXN 3|NOUN|NXN ', '1'

我想将'are'1替换为'where',将ram替换为0。

我应该如何使用哈希映射执行此操作?

1 个答案:

答案 0 :(得分:1)

这个答案基于很多假设,因为你的问题不够明确。但我没有足够的代表发表评论。

如果您对输入句子使用String.split()

String[] words = "ram where are you".split(" ");
// words[0] => ram
// words[1] => where
// words[2] => are
// words[3] => you

看来您的解析树是通过解析输入句子生成的 解析树第一部分中的每个条目对应于输入句子中的单词 解析条目中的第一个数字似乎对应于输入句子中每个单词的索引。

因此,解析条目可以打破为:<word index>|<word category>|<something not clear>

所以,似乎

2|TYPE|nx0e-VPadjn-Vnx1 => are
1|RPron|nx-RP-S => where
0|NOUN|NXN => ram
3|NOUN|NXN => you

基于这些假设,可以使用使用解析树条目构建的散列图 您需要使用key = <word index>; value = <parse entry>将解析条目放入地图 这可以通过将解析树分离到条目然后从每个条目中检索<word index>来完成。

构建映射后,您可以处理输入句子和解析树条目:

String[] words = "ram where are you".split(" ");

Map<Integer, String> entriesMap = getEntriesMap(parseTree); // assuming parseTree is just a String

for(int i = 0; i < words.length; i++) {
    String x = entriesMap.get(i).replaceAll("^" + i + "|", words[i]);
}

填充地图的方法。有多种方法可以做到这一点 使用正确的正则表达式PatternMatcher类可能是最好的方法。

private Map<Integer, String> getEntriesMap(String parseTree) {
    Map<Integer, String> entriesMap = new LinkedHashMap<Integer, String>();

    // assuming parseTree format as: '<parse entries separated by spaces>', '1'
    // use String.split() to split the parseTree by single quote (')
    // first element in returning array would contain the <parse entries separated by spaces>
    // use String.split() again on that element with space to separate parse entries
    // for each <entry> in <parse entries>
    //     split <entry> with pipe (|) and use first element in resulting array as the key and <entry> as the value to put in entriesMap

    return entriesMap;
}

无法弄清楚解析树末尾的,'1'对应。

相关问题