javascript - 给定一个索引位置,我如何拆分出该位置所在的句子?

标签 javascript nlp string-parsing

我正在使用 JavaScript,我的文本是:

Dana's places, we're having people coming to us people wanna buy condos. They want to move quickly and we're just losing out on a lot of great places. Really what would you say this?

如果我的索引位置是 6,我只想得到第一句话:Dana's places, we're having people come to us people wanna buy condos.

如果我的索引位置是 80,我只想得到第二句话:他们想快速行动,而我们只是失去了很多好地方。

如何根据位置解析句子?

最佳答案

如果我没理解错的话,你应该可以

分期。 获取字符串的长度。 根据句子长度确定索引的位置。

考虑到您需要拆分 "?, !"同样,您只需要遍历句子并将它们进一步扁平化。阿卡,再次 split 。

老实说,使用正则表达式和组可能更干净。

这是正则表达式版本

    const paragraph = "Dana's places, we're having people coming to us people wanna buy condos. They want to move quickly and we're just losing out on a lot of great places. Really what would you say this?"


    /**
     * Finds sentence by character index
     * @param index 
     * @param paragraph 
     */
    function findSentenceByCharacterIndex(index, paragraph) {

        const regex = /([^.!?]*[.!?])/gm

        const matches = paragraph.match(regex);

        let cursor = 0;

        let sentenceFound;

        for (const sentence of matches) {

            sentenceFound = sentence;

            cursor += sentence.length;

            if( cursor > index )
            {
                break;
            }
        }

        return sentenceFound;
    }


    const found = findSentenceByCharacterIndex(5, paragraph);

关于javascript - 给定一个索引位置,我如何拆分出该位置所在的句子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52744344/

相关文章:

javascript - d3.js 中带有日期时间 x 轴的柱形图

java - 斯坦福自然语言处理 (StanfordNLP) 词形还原无法处理 -ing 单词

nlp - OpenNLP:无法识别外国名称

nlp - CoNLL 数据格式是什么?

parsing - Vala - 方程解析

php - 为什么 sprintf 在这里返回 false?

java - 正则表达式用于从字符串中删除单引号(所有格名词除外)?

javascript - 如何使用 jquery 淡出多个图像?

javascript - 这是否存在 : HTML Template Renderer Written in JavaScript?

javascript - 向 Highchart 图表添加自定义 Logo