对DOM树中兄弟姐妹的内容进行标记

时间:2011-11-20 08:23:28

标签: xml dom stringtokenizer tf-idf

我计划以后序方式遍历dom树,然后当它遍历每个深度的兄弟姐妹时,对于每个兄弟组,我想获得文本内容中的元素数量。为了说清楚,让我们来看一个例子:

<?xml version="1.0" encoding="UTF-8"?> 
       <title text="title1"> 
           <comment1 id="comment1">
               <data1> this is an example</data1>
               <data2> this example tries to do a demo over a dom tree</data2>
           </comment1>
           <comment2 id="comment2">
               <data3> while it' beeing traversing in postorder fashion </data3>
               <data4> hope it works! </data4>
               <data5> :) </data5>
           </comment2>
       </title> 

例如,我想找出数据1和数据2的charcater的数量以及data3-5 togetehr的数量。 这是我到目前为止编写的代码遍历树和计算TFIDF值,但正如我所提到的,我想分别为每组兄弟姐妹找到TF,任何线索?提前谢谢

lass tree{


    private static int total=0;
    private static double tf=0;
    private static double result=0;
   private static double  TFIDFresult = 0;


   static double TFIDF(int wordcount,String segment,String keyword)


   {

if(segment==null)
    return TFIDFresult;


    StringTokenizer tokenizer =new StringTokenizer(segment) ; 
    while(tokenizer.hasMoreTokens()){
       total++;
        if( tokenizer.nextToken().equals(keyword))
            wordcount++;
        tf= (double) wordcount / total;
       double inverseTF = Math.log10((float) wordcount / 4);
          TFIDFresult = (((double) wordcount / total * inverseTF ));
    }
    return TFIDFresult;
}


public static void check(Node node){
  if (node == null || node.getNodeName() == null)

    return;



  result= TFIDF(total, node.getNodeValue(), "this");

  check(node.getFirstChild());  



System.out.println(node.getNodeValue() != null && node.getNodeValue().trim().length() == 0 ? "" : node);

    check(node.getNextSibling());  

}



    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        File file = new File("d:\\a.xml");
  DocumentBuilderFactory dbf =
  DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document document = db.parse(file);
  document.getDocumentElement().normalize();


  Node b=document.getFirstChild();
  check(b);
  System.out.println(result);



    }
}

ps:手动我假设计算中的doc数量只是出于某种原因。

0 个答案:

没有答案