1

这应该是直截了当的,但由于某种原因,当我将文件下载到我的 SD 卡后尝试计算文件中的字数时,数字似乎已关闭。此外,出现的次数越多,我的结果似乎就越偏离。我使用 Microsoft Word 来验证出现次数(仅使用忽略大小写和整个单词)。为了测试出现的次数,我使用下面的“the_counter”变量。我还确认下载没有问题,完整文件已下载到我的 SD 卡。这让我发疯了——我认为 Word 在这里不会出错,那么下面的代码可能有什么问题?

可能是文件中的空格或特殊字符导致问题 - 有没有办法清理文件来验证这一点?

//Find the directory for the SD Card using the API
        File sdcard = Environment.getExternalStorageDirectory();

        //Get the text file
        File file = new File(sdcard,TEMP_FILE);

        //Read text from file
        //StringBuilder text = new StringBuilder();
        m_tree = new Tree();
        int i=0;
        BufferedReader br = null;
        long the_counter=0;
        try {
            br = new BufferedReader(new FileReader(file));
            String line;
            String []arLine;
            while ((line = br.readLine()) != null) {
                //get each word in line
                if(line.length()==0)
                    continue;
                arLine = line.split("\\s+");

                //now add each word to search tree
                for(i=0;i< arLine.length;++i){
                    m_tree.insert(arLine[i]);
                    if(arLine[i].equalsIgnoreCase("a"))
                        ++the_counter;
                }
            }
           m_sTest = Long.toString(the_counter) ;
           br.close();

我编辑了我的代码以读取每行的每个字符并手动创建单词。我仍然得到相同的结果。

 br = new BufferedReader(new FileReader(file));
            String line;
            String []arLine;
            StringBuilder word = new StringBuilder();
            while ((line = br.readLine()) != null) {
                //check for word at end of last line
                if(word.length()>0){
                    m_tree.insert(word.toString());
                    word.setLength(0);
                }
                char[] lineChars = new char [line.length()];
                line.getChars(0,line.length(),lineChars,0);

                for(char c: lineChars){
                    if(c== ' '){
                        //if we have a word then store and clear then move on
                        if(word.length()>0){
                            m_tree.insert(word.toString());
                            word.setLength(0);
                        }
                    }
                    else{
                        word.append(c);
                    }
                }
4

1 回答 1

0

这个问题是我没有考虑单词之间的特殊字符:即:this-is-four-words 而不是一个。我什至不确定这是正确的语法或写作,但它在这个文件中,它肯定会让我不计其数。

于 2014-07-26T05:05:50.267 回答