【问题标题】:how to find the index of named node in a tregex pattern using stanford corenlp?如何使用stanford corenlp以tregex模式查找命名节点的索引?
【发布时间】:2015-07-31 10:13:35
【问题描述】:

如何在给定的tregex模式中找到与命名节点匹配的字符串的索引?
这是我的意思的一个例子:

text="You can eat fruits such as apples and oranges."
tree="(ROOT (S (NP (PRP You)) (VP (MD can) (VP (VB eat) (NP (NP (NNS fruits)) (PP (JJ such) (IN as) (NP (NNS apples) (CC and) (NNS oranges)))))) (. .)))"
tregex="(JJ < such) $ (IN < as) $ (NP=examples)"
examples="(NP (NNS apples) (CC and) (NNS oranges))"

我想在原始字符串text 中找到命名节点examples 的位置。假设我有一个text 的 HTML,我可能会 &lt;span&gt; 命名节点如下:

<div id="text">You can bring fruits such as <span class="eg">apples and oranges</span>.

Update1:​​leftCharEdge()rightCharEdge() 方法不起作用。似乎它们因空格数或“标记分隔符”而不同。我查看了source code,似乎CharEdge 是通过添加叶子 的长度来计算的。

根据我的观察:

Tree eg = matcher.getNode("examples");
int start = tree.leftCharEdge(eg);
int end = tree.rightCharEdge(eg);
System.out.println("start, end:" + start + "," + end);
//start, end: 21,37

空格不应该也考虑进去吗?将startend 与(大约)之前的空格数抵消似乎可以解决问题:

System.out.println("text[start,end]:" + text.substring(start+6, end+8));
//text[start,end]:apples and oranges

apples and oranges 之前的字数 = 6 = 起始偏移量
apples and oranges 中的字数 = 3 + 开始偏移量 - 1 = 结束偏移量。

【问题讨论】:

    标签: regex stanford-nlp


    【解决方案1】:

    如果您处理的是实际文本(与变量 tree 只是一个单独的 String 的示例不同),那么字符偏移量将嵌入到 TreeCoreLabel 标记中。请参阅下面的示例代码。 (我添加了一条评论,说明 left/rightCharEdge 方法对此没有用。)

      public static void main(String[] args) {
        LexicalizedParser parser = LexicalizedParser.getParserFromFile("edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz", new Options());
    
        String[] texts = {"You can eat fruits such as apples and oranges.",
                "  You can  eat fruits   such as apples and   oranges .",
        };
    
        for (String text : texts) {
          Tree tree = parser.parse(text);
    
          List<CoreLabel> yield = tree.yield(new ArrayList<CoreLabel>());
    
          for (CoreLabel cl : yield) {
            System.out.printf("Word |%s| over char offsets [%d,%d)%n", cl.word(),
                    cl.get(CoreAnnotations.CharacterOffsetBeginAnnotation.class),
                    cl.get(CoreAnnotations.CharacterOffsetEndAnnotation.class));
          }
          System.out.println();
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2013-10-26
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多