2014-06-11 106 views
1

我想通过首先删除停用词并在其上应用词干分析算法来处理文本,最后将它们拆分为单词并将它们保存到文件中。 我做过的一切,我的问题是空格的文件中包含的话如下:从文件java中删除空格

Hi 
teacher 

mother 
sister 
father .... and so on 

的问题是老师和母亲之间的空间。 我想将其删除。我无法弄清楚它的原因。

以下是相关代码的一部分。

public void parseFiles(String filePath) throws FileNotFoundException, IOException { 
    File[] allfiles = new File(filePath).listFiles(); 
    BufferedReader in = null; 
    for (File f : allfiles) { 
     if (f.getName().endsWith(".txt")) { 
      fileNameList.add(f.getName()); 
      Reader fstream = new InputStreamReader(new FileInputStream(f),"UTF-8"); 
      in = new BufferedReader(fstream); 
      StringBuilder sb = new StringBuilder(); 
      String s=null; 
      String word = null; 
      while ((s = in.readLine()) != null) { 
       s=s.trim().replaceAll("[^A-Za-z0-9]", " ");  //remove all punctuation for English text 
       Scanner input = new Scanner(s); 
        while(input.hasNext()) {    
         word= input.next(); 
         word=word.trim().toLowerCase(); 
       if(stopword.isStopword(word)==true) 
       { 
        word= word.replace(word, ""); 
       } 
       String stemmed=stem.stem (word); 
       sb.append(stemmed+"\t"); 

        } 
        //System.out.print(sb); 

      } 
      String[] tokenizedTerms = sb.toString().replaceAll("[\\W&&[^\\s]]", "").split("\\W+"); //to get individual terms (English) 

      for (String term : tokenizedTerms) { 
       if (!allTerms.contains(term)) { //avoid duplicate entry 
       allTerms.add(term); 
        System.out.print(term+"\t"); 
       } 
      } 
      termsDocsArray.add(tokenizedTerms); 
     } 
    } 
    //System.out.print("file names="+fileNameList); 
} 

请帮忙。 感谢

回答

4

为什么不使用的,如果检查,如果该行是空的?

while ((s = in.readLine()) != null) { 
    if (!s.trim().isEmpty()) { 
    ... 
    } 
} 
+2

我还要补充一个'TRIM()',你可以考虑空字符串,如果它仅仅是由空格 – BackSlash

+0

你说得对,感谢的话。 – Christian

+1

你也可以使用'isEmpty()'方法 –

1

尝试这样的事情来消除所有空行:

String yourText = "teacher\nmother etc.."; 
String adjustedText = yourText.replaceAll("(?m)^[ \t]*\r?\n", ""); 
+0

谢谢你,我的问题解决了 – Souad

1

在while循环添加此条件也

,而((S = in.readLine())!= NULL & &(!(StringUtils.isBlank(S)))){

//你的逻辑在这里。 }

+0

谢谢我解决了这个问题 – Souad