我正在使用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 coming to us people wanna buy condos.
如果我有80的索引位置,我只想得到第二句话:They want to move quickly and we're just losing out on a lot of great places.
如何根据位置来解析句子?
发布于 2018-10-10 16:16:03
如果我没听错,你应该
分期付款。得到字符串的长度。根据句子长度确定索引指向的位置。
考虑到你需要分开"?,“同样,你只需要遍历这些句子,然后再把它们压平。又分开了。
老实说,使用正则表达式和组可能更干净。
这里是regex版本的
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);发布于 2018-10-10 16:05:37
如果你分期付款的话。string对象有一个名为split的原型方法,该方法返回拆分字符串的数组。在下面的示例中,str是一个保存字符串的变量。
const str = 'first sentence. Second sentence. third sentence';
const sentences = str.split('.');
sentences[0] // first sentence
sentences[1] // second sentence, etc发布于 2018-10-10 16:24:07
与其尝试使用Array.split,不如对字符串按字符进行一些传统的字符解析。因为我们知道我们要找的是什么索引,所以我们可以简单地看看句子的开头和结尾。
句子是怎么结束的?通常,使用.**,** !**,或** ? -知道这一点,我们可以测试这些字符,并决定字符串的哪一部分,我们应该切分并返回到程序。如果在我们选择的索引之前没有sentence enders(a.e. )。?!.)我们假设字符串的开头是当前语句(0)的开头--我们在所选索引之后也这样做,但如果索引后面没有句柄,则分配str.length。
let str = "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?";
let getSentence = (ind, str) => {
let beg, end, flag, sentenceEnder = ["!", ".", "?"];
Array.from(str).forEach((c, c_index) => {
if(c_index < ind && sentenceEnder.includes(c)) {
beg = c_index + 1;
}
if (flag) return;
if (c_index >= ind && sentenceEnder.includes(c)) {
end = c_index;
flag = true;
}
});
end = end || str.length;
beg = beg || 0;
return str.slice(beg, end);
}
console.log(getSentence(10, str));
console.log(getSentence(80, str));
https://stackoverflow.com/questions/52744344
复制相似问题