如何修复响应文本?

How can I fix response text?

我使用 Google Cloud Vision Api (Text_Detection) 它工作正常但是当我 return 从 Google 回答时,消息样式如下图片

我只想要一个文本,例如 "ACADEMIC PLANNER" 那么如何删除 Academic "null:" 和其他词的前面?

图片,例如

这是我的代码;

private String convertResponseToString(BatchAnnotateImagesResponse response) {
    String message = "I found these things:\n\n";

    List<EntityAnnotation> labels = response.getResponses().get(0).getTextAnnotations();
    if (labels != null) {
        for (EntityAnnotation label : labels) {
            message += String.format("%.3f: %s", label.getScore(), label.getDescription());
            message += "\n";
        }
    } else {
        message += "nothing";
    }

    return message;
}

如果我正确理解你的问题,那么你只需要使用 String class 的 substring() and trim() 方法清理标签的 描述 .这是您的代码的修改版本:

private String convertResponseToString(BatchAnnotateImagesResponse response) {

    String message = "I found these things:\n\n";
    List<EntityAnnotation> labels = response.getResponses().get(0).getTextAnnotations();
    if (labels != null) {
        for (EntityAnnotation label : labels) {
             // 5=index of the character after "null:" (zero-based array counting), trim() removes whitespace on both sides of the string.
            message += String.format("%.3f: %s", label.getScore(), label.getDescription().substring(5).trim());
            message += "\n";
        }
    } else {
        message += "nothing";
    }

    return message;
}

PS: 从文档中,getDescription() method returns a string and getScore() returns 一个浮点数。我打赌分数不会给你带来任何问题。我没有测试你的实际数据。

你的分数大概是null。这样做:

message += String.format("%s", label.getDescription());

为了只有一个词,你的方法看起来像这样:

private String convertResponseToString(BatchAnnotateImagesResponse response) {
    String message = "I found these things:\n\n";

    List<EntityAnnotation> label = response.getResponses().get(0).getTextAnnotations().get(0);
    if (label != null) {
            message += String.format("%s", label.getDescription());
            message += "\n";
    } else {
        message += "nothing";
    }

    return message;
}

答案:

private String convertResponseToString(BatchAnnotateImagesResponse response) {
    String message = "I found these things:\n\n";
    List<EntityAnnotation> labels = response.getResponses().get(0).getTextAnnotations();
    if (labels != null) {
      message += labels.get(0).getDescription();
    } else {
      message += "nothing";
    }
    return message;
}