I have data on different formats. I want that first the Quantity is extracted from the input string than the Unit is extracted and the remaining text should consider as an item.
Code.java
public String itemsProcesing(List<String> items) throws IOException {
List<String> list = items;
List<String> unitList = Arrays.asList("g", "tbsp", "cm", "kg"");
List<String> quantityList = Arrays.asList("Full", "Quarter", "Half", "3 Quarter", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
for (String s : list) {
String[] strArr = s.split(" ");
if (strArr.length == 2) {
String newStr = rewriteString(strArr, quantityList);
strArr = newStr.split(" ");
}
String[] itemLine = new String[3];
for (int i = 0; i < strArr.length; i++) {
String str = strArr[i];
int index = findValueLocation(str, unitList);
itemLine[index] = str;
}
String line = createLineForCSV(itemLine);
writeToFile(line);
}
return "done";
}
private static int findValueLocation(String str, List<String> unitList) {
boolean b = Pattern.matches("\\d{1,3}|\\d/\\d|\\d/\\d[*]\\d|\\d{1,3}[*]\\d{1,3}|\\d{1,3}[*]\\d{1,3}|\\d{1,3}[-]\\d{1,3}|\\d{1,3} [-] \\d{1,3}|\\d.\\d|\\\\d{1,3} - \\\\d{1,3}| \\\\d{1,3} - \\\\d{1,3}| \\\\d{1,3}-\\\\d{1,3}", str);
if (b) {
return 0;
}
for (String unit : unitList) {
if (unit.equals(str)) {
return 1;
}
}
return 2;
}
private static String createLineForCSV(String[] itemLine) {
StringBuilder sb = new StringBuilder();
sb.append(itemLine[0]).append(",");
sb.append(itemLine[1]).append(",");
sb.append(itemLine[2]);
return sb.toString();
}
private static void writeToFile(String line) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter("csv_file.csv", true));
writer.write(line);
writer.newLine();
writer.close();
}
private static String rewriteString(String[] arr, List<String> quantityList) {
String strOne = arr[0];
String strTwo = arr[1];
String newStr = "";
for (String quantity : quantityList) {
if (strOne.contains(quantity)) {
// 8g carrots becomes "8 g carrots"
newStr = quantity + " " + strOne.substring(quantity.length()) + " " + strTwo;
break;
} else if (strTwo.contains(quantity)) {
newStr = quantity + " " + strTwo.substring(quantity.length()) + " " + strOne;
break;
}
}
return newStr;
}
Input data 1-2 tbsp soya sauce
Ouptut : 1-2,tbsp,sauce
Required Output: 1-2,tbsp,soya sauce
How I could get the required results.
The problem is here at this line in items processing :
int index = findValueLocation(str, unitList);
itemLine[index] = str;
The 'findValueLocation' function will return 2 for both strings 'soya' and 'sauce'. Now it overwrites the string 'soya' and writes 'sauce' on index 2. You should concatenate the string if the value being returned is 2.
`
int index = findValueLocation(str, unitList);
if(index == 2){
itemLine[index] += str;
}else{
itemLine[index] = str;
}
`