问题
FileDataModel accepts data in the format
userId,itemId,pref(long,long,Double).
At the moment I have some itemId that consist of an 'x' at the end of the number. How do I edit the some of the itemID such that it removes the 'x' ? Is it possible to do this with a simple try catch statement?
DataModel model = null;
try{
model = new FileDataModel(new File("book_data/BX-Book-Ratings.csv"));
}catch(NumberFormatException e){
REMOVE X
}
CODE:
DataModel model = new FileDataModel(new File("book_data/BX-Book-Ratings.csv"));
ERROR:
Exception in thread "main" java.lang.NumberFormatException: For input string: "034545104X"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:589)
at java.lang.Long.parseLong(Long.java:631)
DATA:
276725,034545104X,0
276726,155061224,5
276727,446520802,0
276729,052165615X,3
回答1:
One way would be to run a pre-processor on the file that transforms it's content to ensure it is compatible with FileDataModel
. If your data format is very simple you may just use a regular expression replace. Otherwise I'd suggest having a parser that can bring the data into memory, then perform your manipulation with a transformer and finally save back the results with a serializer.
Something like:
File file = new File("book_data/BX-Book-Ratings.csv");
FileDataModelTransformer transformer = new FileDataModelTransformer();
transformer.transformInPlace(file);
DataModel model = new FileDataModel(file);
By the way, it's more flexible to rely on streams or buffers than File
.
回答2:
The easiest way, IMHO, would be to just use an if statement:
String itemIdStr = "034545104X"; // for example
if (itenIdStr.endsWith("X")) {
itemIdStr = itemIdStr.substring(0, itemIdStr.length() - 1);
}
long itemId = Long.parseLong(itemIdStr);
来源:https://stackoverflow.com/questions/40196498/remove-character-from-integer