前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >优雅计算坐标(对接算法)

优雅计算坐标(对接算法)

作者头像
用户10136162
发布2023-10-30 14:38:40
1200
发布2023-10-30 14:38:40
举报
文章被收录于专栏:Eliauk的小窝

需求

首先是有一段档案文章在没有换行符的情况下发送给了算法,算法识别出来了敏感词与敏感句以及他们的坐标(此时的坐标是没有换行符/n的情况下的) 但是我们的原始档案文章是有换行符的因为要让前端去解析,但是现在问题就出现了 因为前端展示界面要有换行所以给前端的数据要携带/n,但是现在要把敏感词和敏感句高亮,如果我们的坐标还是没有/n的坐标前端就没办法匹配高亮了 有些人可能会说直接index不就好了? ,但是如果词或句子在/n之间呢,那怎么计算,所以我写了一个算法来计算敏感词句的start和end

代码语言:javascript
复制

/**
 * 寻找给定文本中换行字符的索引。
 * @param text 需要搜索换行字符的文本。
 * @return 一个包含换行字符索引的整数数组。
 */
Function<String, int[]> findNewLineIndices = text -> {
    ArrayList<Integer> indicesList = new ArrayList<>();
    int index = text.indexOf('\n');
    while (index != -1) {
        indicesList.add(index - indicesList.size());
        index = text.indexOf('\n', index + 1);
    }
    int[] indicesArray = new int[indicesList.size()];
    for (int i = 0; i < indicesList.size(); i++) {
        indicesArray[i] = indicesList.get(i);
    }
    return indicesArray;
};

/**
 * 在文本字符串中找到一个句子的起始和结束索引。
 * 如果整个句子没有被找到,它会尝试找到存在于文本中的句子的一个子字符串。
 * @param sentence 要查找的句子。
 * @param text 要搜索的文本。
 * @return 一个包含两个元素的整数数组:起始索引和结束索引。
 */
BiFunction<String, String, int[]> findSentence = (sentence, text) -> {
    int sentenceLength = sentence.length();
    int[] result = new int[]{0, 0};
    while (sentence.length() > 4 /* 最小句子长度 */ && !text.contains(sentence)) {
        sentence = sentence.substring(0, sentence.length() - 1);
    }
    int index = text.indexOf(sentence);
    if (index >= 0 && !sentence.isEmpty()) {
        return new int[]{index, index + sentenceLength};
    } else {
        return result;
    }
};

/**
 * 确定起始节点周围的索引。
 * 具体来说,这个函数找到起始节点索引之前的换行字符的数量。
 * @param indices 表示换行字符的一个索引数组。
 * @param startNode 起始节点索引。
 * @return 一个包含起始节点前索引和起始节点与结束节点之间的换行字符数量的整数数组。
 */
BiFunction<int[], Integer, int[]> findCountIndices = (indices, startNode) -> {
    int indexBeforeStart = -1;
    int indicesBetween = 0;
    for (int i = 0; i < indices.length; i++) {
        if (indices[i] > startNode) {
            indexBeforeStart = i;
            break;
        }
    }
    return new int[]{indexBeforeStart, indicesBetween};
};



String replace = artificialText.replaceAll("\\n", "");
int[] newLineIndices = findNewLineIndices.apply(artificialText);
int[] sentenceIndices = findSentence.apply(cleanSentenceText, replace);
int[] countIndices = findCountIndices.apply(newLineIndices, sentenceIndices[0]);

jsonObject.add("start", new JsonPrimitive(sentenceIndies[0] + countIndices[0]));
jsonObject.add("end", new JsonPrimitive(sentenceIndices[1] + countIndices[0] + countIndices[1]));
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-10-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 需求
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档