我有不同格式的数据。我希望首先从输入字符串中提取数量,然后提取单位,其余文本应视为项目。
代码.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
我如何获得所需的结果。
最佳答案
我认为仅构建一个详尽的测量单位列表并沿其拆分字符串就足够了。那么你就不需要解析金额了。
类似这样的事情:
Pattern p=Pattern.compile("(.*?)\\s*(tbsp|k?g|cup|c?m)\\s*(.*)");
List<String> tests=Arrays.asList(
"16g salt",
"1 kg apple",
"1 1/2 tbsp sugar");
for(String s:tests){
Matcher m=p.matcher(s);
if(m.matches())
System.out.println(Arrays.asList(m.group(1),m.group(2),m.group(3)));
}
输出(来自 https://ideone.com/9kbozK ):
[16, g, salt] [1, kg, apple] [1 1/2, tbsp, sugar]
在现实生活中,应该有一个 else
分支来捕获输入中可能存在的错误(或无法识别的单元)。
关于java - 使用 JAVA 将字符串拆分为多个部分并存储为 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60024672/