如何修复响应文本?

时间:2016-10-31 20:17:07

标签: android response

我使用Google Cloud Vision Api(Text_Detection)它正常工作但是当我从Google返回答案时,消息样式就像图像

我只想要一个文本,例如“学术规划师”,那么如何删除学术前线“null:”等词?

图像

enter image description here

这是我的代码;

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

3 个答案:

答案 0 :(得分:0)

您的分数可能是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;
}

答案 1 :(得分:0)

答案:

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

答案 2 :(得分:-1)

如果我正确理解了您的问题,那么您只需要使用String类的substring()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()方法返回一个字符串,getScore()返回一个Float。我打赌分数不会给你任何问题。我没有测试你的实际数据。