将一个字符串分成 3 部分并在 JAVA 中导出为 CSV

Dividing a string into 3 parts and export to CSV in JAVA

我有一个字符串“1 kg potatoes”,而 1 是数量,kg 是单位,potatoes 是项目。我希望编译器读取一个字符串并匹配“unit_list & quantity_list”(见下面的代码)。并将结果保存到 CSV 文件中的 3 列中。

   List<String> unit_list = Arrays.asList("g", "kg","ml","l");          
   List<String> quantity_list = Arrays.asList("Full", "Quarter", "Half", "3 Quarter", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0");                                                                                                   
                                                                                                                                                                                                                                                               
   String input = "1 kg potatoes";                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
                                                                                                                                                                            
   if (unit_list.equals(input)) {                                                                                                                                                                                                               
       System.out.println("Unit Detected");                                                                                                                                                                                                                    
   }  
                                                                                                                                                                                                                                                         
   if (quantity_list.equals(input)) {                                                                                                                                                                                                    
       System.out.println("Quantity Detected");                                                                                                                                                                                                                
   }                                                                                                                                                                                                                                                           

Expected Output in CSV File

Quantity, Unit, Item

1, kg , potatoes

但这对我不起作用。请帮我做一下。

编辑:基于您所说的“8 克胡萝卜”可能是“8 克胡萝卜”这一事实,我更新了原始代码并在底部添加了一个新方法。

这是我想出的解决方案。既然你说不能保证顺序,而且我们不需要检查 "item" 是否有效,我是这样做的:

  public static void parseToCSV() throws IOException {
    List<String> list = generateList();
    List<String> unitList = Arrays.asList("g", "kg","ml","l");          
    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(" ");
      // Checks if the String array is too short for what we need(i.e "8g carrots" instead of "8 g carrots")
      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, quantityList, unitList);
        itemLine[index] = str;
      }
      String line = createLineForCSV(itemLine);
      writeToFile(line);
    }

  }

  private static List<String> generateList() {
    List<String> list = new ArrayList<>();
    String inputOne = "1 kg potatoes";
    String inputTwo = "3 g juice";
    String inputThree = "8g carrots";
    list.add(inputOne);
    list.add(inputTwo);
    list.add(inputThree);
    return list;
  }

  /**
   * Return the index where the value should go in a comma separated String. If the
   * value is not found in either list then it is the item by default.
   */
  private static int findValueLocation(String str, List<String> quantityList, List<String> unitList) {                                                                                                 

    for(String quantity : quantityList) {
      if(quantity.equals(str)) {
        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 {
    // Set to true for append mode
    BufferedWriter writer = new BufferedWriter(new FileWriter("csv_file.csv", true));
    writer.write(line);
    writer.newLine();
    writer.close();
  }

这在我测试时有效。唯一的问题是每次 运行 它都会附加到 CSV 文件中。如果您想要一个选项来清除文件以便您可以写入所有新数据,那么您可以添加此方法:

  private static void clearFile() throws IOException {
    FileWriter writer = new FileWriter("csv_file.csv", false);
    writer.write("");
    writer.close();
  }

编辑:修复“8g”而非“8g”问题的新方法。这样做是检查拆分字符串的长度是否为 2。如果是,则它没有正确分隔。我们检查 quantityList,因为它永远不应该是 "g8 carrots"。我们找到数量,并创建一个 return 的新字符串作为正确制作的字符串。有点棘手的解决方案,但对我有用。

  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;
  }

希望对您有所帮助!