[英]Pre-processing txt document into a hashmap with String as key, and Integer ArrayList as value
對於一項作業,我被要求將txt文檔預處理為一個哈希表,以便具有高效的單詞搜索功能。 “為了實現高效的單詞搜索,您的代碼將對文檔進行預處理,並將在文檔中找到的所有單詞以及在哈希表中找到它們的行存儲在一起(單詞是鍵,而行是值)。” 我無法弄清楚自己的一生,為什么我無法用新的值替換鍵中的舊值。 這是預處理文檔的構造函數。
HashMap<String, ArrayList<Integer>> map = new HashMap<String, ArrayList<Integer>>();
public wordSearch() {
char charChecker;
String word;
ArrayList<Integer> count = new ArrayList<Integer>();
try{
URL url = new URL("http://homes.soic.indiana.edu/classes/spring2016/csci/c343-yye/docu.txt");
Scanner in = new Scanner(url.openStream());
int lineNumber = 1;
while(in.hasNext()) {
String str = in.nextLine();
for(int i = 0; i < str.length(); i++) {
for(int j = i+1; j < str.length(); j++) {
charChecker = str.charAt(j);
//check for word
if(charChecker == ' ' ||
charChecker == ',' ||
charChecker == '.' ||
charChecker == '\n') {
word = str.substring(i, j);
//if word is already in HashMap
if(this.map.containsKey(word)) {
count = this.map.get(word);
count.add(lineNumber);
//System.out.println("[" + word + ", " + count.toString() + "]");
this.map.put(word, count);
}
//otherwise add word to HashMap
else {
count.add(lineNumber);
System.out.println(count.toString());
this.map.put(word, count);
//System.out.println("[" + word + ", " + count.toString() + "]");
}
i = j+1;
count.clear();
}
}
}
lineNumber+=1;
}
in.close();
}catch(IOException e) {
System.out.println(e.getMessage());
}
System.out.println(this.map.toString());
}
關於從這里出發的任何建議將不勝感激。
代替count.clear();
使用count = new ArrayList<Integer>();
現有代碼的所有鍵都具有相同的計數實例
一種替代方法是檢查單詞的行號是否存在。
HashMap<String, List<Integer>> wordMap = new HashMap<>();
List<Integer> lineNumbers;
if(...){
word = str.substring(i, j);
if ((lineNumbers = wordMap.get(word)) != null){
lineNumbers.add(lineNumber);
}else {
lineNumbers = new ArrayList<>();
lineNumbers.add(lineNumber);
wordMap.put(word, lineNumbers);
}
i = j+1
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.