[英]reading CSV file into hashmap
我有一個CSV文件,其中包含以下字段:字段1,字段2,字段3,頻率,我想將其分配給Java中的哈希映射變量。 從下面的代碼這里是掃描文件,並計算頻率的每一行,但我有一個頻率的文件已經所以我只需要讀了幾行。 所以我取代
// split the transaction into items
與
String[] lineSplited = line.split(" ");
String itemString = lineSplited[0];
Integer count = Integer.valueOf(lineSplited[1]);
mapSupport.put(itemString, count);
在原始代碼中
private void DetermineFrequencyOfSingleItems(String input,
final Map<String, Integer> mapSupport)
throws FileNotFoundException, IOException {
//Create object for reading the input file
BufferedReader reader = new BufferedReader(new FileReader(input));
String line;
// for each line (transaction) until the end of file
while( ((line = reader.readLine())!= null)){
// if the line is a comment, is empty or is a
// kind of metadata
if (line.isEmpty() == true ||
line.charAt(0) == '#' || line.charAt(0) == '%'
|| line.charAt(0) == '@') {
continue;
}
// split the transaction into items
String[] lineSplited = line.split(" ");
// for each item in the transaction
for(String itemString : lineSplited){
// increase the support count of the item
Integer count = mapSupport.get(itemString);
if(count == null){
mapSupport.put(itemString, 1);
}else{
mapSupport.put(itemString, ++count);
}
}
// increase the transaction count
transactionCount++;
}
// close the input file
reader.close();
}
但這不起作用,有什么建議嗎?
在原始程序中,對行頻進行計數,因此使用“”(空格)分隔CSV行沒有區別。
但是,由於您正在讀取數據,因此在用作映射中的鍵或解析為Integer之前,必須使用“,”(逗號)進行拆分並修剪String。
並且請具體說明您的問題以及遇到的錯誤類型。
由於您的文件以制表符分隔,並且您希望最后一個字段為count,其余字段為鍵值,請嘗試
String frequency = line.substring(line.lastIndexOf('\t')+1);// Parse as Integer
String key=line.substring(0, line.lastIndexOf('\t'));
mapSupport.put(key,Integer.parseInt(frequency));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.