日期:2014-05-20  浏览次数:20795 次

关于文档扫描问题
大师们,我有关于文档扫描问题想问问大家。
比如这是文档:
{
123
123
123
}
{
123
123
123
}
{
123
123
123
}

怎么把每个{}里面的内容扫描出来。
条件是第一个123是做key放进Hashmp
其他123放进ArrayList
然后123key 指向 每个 ArrayList

我需要比较快的扫描方法。

谢谢!!

下面是本人自己写的code
大家看下有什么 多余的。

private static HashMap<String, ArrayList<String>> GetAllWords()
{
try{
Scanner s = new Scanner(f);
while(s.hasNext())
{
//If you want to add word instead of sentence, change nextLine to next
String st = s.nextLine();
if(st.equals("{"))
{
String key = s.nextLine();
as = new ArrayList<String>();
while(!st.equals("}")){
String sthToAdd = s.nextLine();
if(!sthToAdd.equals("{") && !sthToAdd.equals("}"))
{
as.add(sthToAdd);
HM.put(key, as);
}
else
break;
}
}
}
}
catch(Exception e){
System.out.println("error");}
return HM;
}

------解决方案--------------------
程序应该可用,不过逻辑看起来较为复杂,建议用“有穷自动状态机”,除了能解决复杂结构问题外,还可以纠错:

Java code

public class TextToStruct {

    public static void main(String[] args) {
        textToMapList();
    }

    enum STATUS {
        WaitForNew, WaitForKey, WaitForValue
    }

    public static void textToMapList() {
        String source = "{\n123\n121\n122\n}\n{\n333\n113\n113\n}\n{\n123\n121\n123\n}\n";

        Map<String, List> map = new HashMap<String, List>(); // 存放结果的Map
        STATUS status = STATUS.WaitForNew; // 有穷状态自动机的状态标志
        List<String> tmp = null; // 存放当前Value的临时List
        Scanner sc = new Scanner(source); // 输入源
        // 有穷状态自动机
        while (sc.hasNextLine()) {
            String line = sc.nextLine().trim();
            if (line.length() == 0) {
                continue; // 空行直接忽略
            }
            // 状态自动处理器
            switch (status) {
            case WaitForNew: // 需要处理 {
                if ("{".equals(line)) {
                    status = STATUS.WaitForKey;
                } else { // 发现源数据结构错误,需要起始标志 {,但没有得到
                    throw new RuntimeException("Except {, but get: " + line);
                }
                break;
            case WaitForKey: // 需要处理 Key
                if (!map.containsKey(line)) { // 查找是否已经有过该Key
                    map.put(line, new ArrayList<String>());
                }
                tmp = map.get(line); // 准备List
                status = STATUS.WaitForValue;
                break;
            case WaitForValue: // 需要处理 值 和 }
                if ("}".equals(line)) {
                    tmp = null;
                    status = STATUS.WaitForNew;
                } else {
                    tmp.add(line);
                }
                break;
            }
        }

        // 输出结果
        for (String key : map.keySet()) {
            System.out.println(key + ": " + map.get(key));
        }
    }
}