簡體   English   中英

使用掃描儀將單詞的出現次數及其計數存儲在文件中。(Java)

[英]Store occurences of words in a file and their count,using Scanner.( Java )

這是代碼:

        Scanner scan = new Scanner(new FileReader ("C:\\mytext.txt"));
        HashMap<String, Integer> listOfWords = new HashMap<String, Integer>();

        while(scan.hasNextLine())
        {
            Scanner innerScan = new Scanner(scan.nextLine());
            boolean wordExistence ;
            while(wordExistence = innerScan.hasNext())
            {
                String word = innerScan.next(); 
                int countWord = 0;
                if(!listOfWords.containsKey(word)){ already
                    listOfWords.put(word, 1); 
                }else{
                    countWord = listOfWords.get(word) + 1; 
                    listOfWords.remove(word);
                    listOfWords.put(word, countWord); 
                }
            }
        }

        System.out.println(listOfWords.toString());

問題是,我的輸出包含像這樣的詞:

document.Because=1 document.This=1 space.=1

我該如何處理正在發生的句號?(對於其他問題,我認為任何句子終止符都會成為問題,例如問號或感嘆號)。

查看Scanner API的類說明,特別是有關使用除空格之外的定界符的段落。

Scanner使用任何空格作為默認定界符。 您可以調用Scanner實例的useDelimiter()並指定您自己的正則表達式用作定界符。

如果您希望不僅使用空格分隔符來分割輸入,還可以使用. 和問號/感嘆號,您將必須定義一個Pattern ,然后使用useDelimiterdoc )將其應用於您的掃描儀。

也許您想修改以下答案以優化速度。

    final Pattern WORD = Pattern.compile("\\w+");
    while(scan.hasNextLine())
    {
        Scanner innerScan = new Scanner(scan.nextLine());
        while(innerScan.hasNext(WORD))
        {
            String word = innerScan.next(WORD); 
            if(!listOfWords.containsKey(word)){
                listOfWords.put(word, 1); 
            }else{
                int countWord = listOfWords.get(word) + 1; 
                //listOfWords.remove(word);
                listOfWords.put(word, countWord); 
            }
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM