【lab2】scanner读文件

    public GraphPoet(File corpus) throws IOException {
        try {
            File file = new File("assets/test.txt");
            Scanner scanner = new Scanner(corpus);
            scanner.useDelimiter("\\s+");
            String preWord = null;
            String thisWord;
            int i=0;
            while (scanner.hasNext()) {
                thisWord = scanner.next();

                graph.add(thisWord.toLowerCase());

                    if(i>0){
                        //不存在边,加入
                        int lastEdgeWeight = this.graph.set(preWord.toLowerCase(), thisWord.toLowerCase(), 1);
                        //如果边已经存在了,weight++
                        if (lastEdgeWeight != 0)
                            this.graph.set(preWord.toLowerCase(), thisWord.toLowerCase(), lastEdgeWeight + 1);
                    }
                i=1;
                preWord=thisWord;

                System.out.println();

            }

            scanner.close();

        } catch (Exception e) {
            throw new      IOException("File Not Readable or Not Found");

        }
    public GraphPoet(File corpus) throws IOException {

        //读文件
        try{
            BufferedReader reader=new BufferedReader(new FileReader(corpus));
            BufferedReader bReader = new BufferedReader(reader);
            String line;
            List<String> words=new ArrayList<>();
            while ((line = bReader.readLine()) != null) {
                //单词小写加入图
                words.clear();
                words.addAll(Arrays.asList(line.split("\\s+")));
                int num=words.size();
                for(int i=0;i<num;i++){
                    graph.add(words.get(i).toLowerCase());
                    if(i>0){
                        //不存在边,加入
                        int lastEdgeWeight = this.graph.set(words.get(i-1).toLowerCase(), words.get(i).toLowerCase(), 1);
                        //如果边已经存在了,weight++
                        if (lastEdgeWeight != 0)
                            this.graph.set(words.get(i-1).toLowerCase(), words.get(i).toLowerCase(), lastEdgeWeight + 1);
                    }
                }

            }
            bReader.close();
            checkRep();

        }catch (Exception e){
            throw new IOException("File Not Readable or Not Found");
        }
        //throw new RuntimeException("not implemented");
    }
    ```
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值