[英]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()
並指定您自己的正則表達式用作定界符。
也許您想修改以下答案以優化速度。
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.