2015-10-19 59 views
2

我需要创建代码来计算.txt文件中的单个单词。格式必须是类似于:在大文本文件中计算单个单词时引用问题

the - 10 
text - 1 
has - 5 
etc. 

我遇到,我不能似乎解决一个问题: 文本使用的quoes撇号,所以我的代码解析的话,如“不,一点也不看到'不一样'。我不知道如何解决这个问题。

这是代码的特定部分。我必须在分隔符中使用正则表达式。

static int findAndCountWords (Scanner scanner, String[] words, int [] freqs) 
{ 
    assert (words != null)&&(freqs != null): "findAndCountWords doesn't work."; 
    int nr=0; 
    while (scanner.hasNext()) 
    { 
     String word = scanner.next(); 
     word = word.toLowerCase(); 
     scanner.useDelimiter("[^a-z]"); 
     //|[^a-z]+[\\'][^a-z]+ 
     if (updateWord(word, words, freqs, nr)) 
     nr++; 
    } 
    return nr; 
} 
+0

什么APOSTROPH? '.useDelimiter(“[^ a-z']”)'? – 2015-10-19 11:42:24

+0

你可能会开始使用除法器''\\ W * \\ s + \\ W *“'。 – jaco0646

回答

0

我会先从您的文字中删除任何撇号。

您可以使用Apache公共做到这一点:

str = StringUtils.stripStart(str,"'") 

或您的匹配:

Pattern pattern = Pattern.compile("(?:^')|(?:'$)); // starts or ends with apostrophe 
str = pattern.matcher(str).replaceAll(""); // not anymore 

(我没有测试代码,也许一些bug)有关将

相关问题