语法分析代码

来源:互联网 发布:1.1初识动画软件教案 编辑:程序博客网 时间:2024/06/05 18:04

import java.util.List;

import test.Analysis;
import test.Grammar;


public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  String[][] table = {
    {"1", "2", "3", ":", "/", ".", "?", ";",  "//"},
    
    {"",  "1",  "",  "",  "",  "",  "",  "",  ""},
    {"",  "",   "",  "2", "",  "5", "",  "",  ""},
    {"",  "",   "",  "",  "",  "",  "",  "",  "3"},
    {"",  "4",  "",  "",  "",  "",  "",  "",  ""},
    {"",  "",   "",  "",  "",  "5", "",  "",  ""},
    {"",  "6",  "",  "",  "",  "",  "",  "",  ""},
    {"",  "",   "",  "7", "0", "5", "0", "0", ""},
    {"8", "",   "",  "",  "",  "",  "",  "",  ""},
    {"",  "",   "",  "",  "0", "",  "0", "0", ""}
  };
  
  Grammar grammar = new Grammar(table);
  
  Analysis an = new Analysis();
  
  List list = an.scan("https://www.google.w.cn:80/search?hl=zh-CN你好&newwindow=1&q=fy+%E5%88%A4%E6%96%AD&aq=f&oq=&aqi=");
  
  //an.print(list);
  
  String result = grammar.analysis2(list);
  
  System.out.println(result);
  
 }
}

 

 

 

 

package test;

import java.util.HashMap;
import java.util.List;

public class Grammar {
 private HashMap map = new HashMap();
 
 public Grammar(String[][] table) {
  String[] temp;
  String[] v;
  int s = table.length;
  int l = 0;
  
  temp = table[0];
  l = temp.length;
  
  for(int i=1;i<s;i++) {
   HashMap m = new HashMap();
   v = table[i];
   for(int j=0;j<l;j++) {
    String t = v[j];
    if(t == null || t.length() ==0) {
     t = "-1";
    }
    m.put(temp[j], t);
   }
   
   this.map.put(i-1, m);
  }
  
 }
 
 public String analysis2(List<Item> result) {
  StringBuilder builder = new StringBuilder();
  
  int state = 0;
  int s;
  
  s = result.size();
  
  for(int i=0;i<s;i++) {
   builder.append(result.get(i).getContent());
   Item item = result.get(i);
   String temp;
   if(item.getType() == 1 || item.getType() == 2 || item.getType() == 3) {
    HashMap t = (HashMap) map.get(state);
    temp = (String) t.get(String.valueOf(item.getType()));
   } else {
    HashMap t = (HashMap) map.get(state);
    temp = (String) t.get(item.getContent());
   }
   if(temp != null) {
    int v = 0;
    try{
     v = Integer.parseInt(temp);
    } catch(Exception e) {
     v = -1;
    }
    if(v == 0) {
     break;
    } else if(v == -1) {
     builder.delete(0, builder.length());
     break;
    } else {
     state = v;
    }
   } else {
    builder.delete(0, builder.length());
    break;
   }
  }
  
  return builder.toString();
 }
  
}

 

 

原创粉丝点击