Javascript 给定一个索引位置,我如何划分该位置所在的句子?
我正在使用JavaScript,我的文本是:Javascript 给定一个索引位置,我如何划分该位置所在的句子?,javascript,nlp,string-parsing,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,有人来找我们,有
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,有人来找我们,有人想买公寓。
如果我的索引位置是80
,我只想得到第二句话:他们想快速行动,而我们正在失去很多好地方。
如何根据位置解析句子?如果按句点拆分。string对象有一个名为split的原型方法,该方法返回被拆分字符串的数组。在下面的示例中,
str
是一个保存字符串的变量
const str = 'first sentence. Second sentence. third sentence';
const sentences = str.split('.');
sentences[0] // first sentence
sentences[1] // second sentence, etc
如果我理解正确,你应该能够 分期付款。 获取字符串的长度。 根据句子长度确定索引的位置 考虑到你也需要在“?,!”上分开,你只需要在句子中循环并进一步展平它们。阿卡,又分手了 老实说,可能需要使用正则表达式和组 这是正则表达式的版本
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);
与其尝试使用
Array.split
,不如对字符串进行一些传统的逐字符分析。因为我们知道我们在寻找什么索引,所以我们可以简单地查找句子的开头和结尾
一个句子怎么结尾?通常使用,
或a?
-知道这一点,我们可以测试这些字符,并决定应该切掉字符串的哪一部分并返回程序。如果在我们选择的索引之前没有句子结尾
(a.e.?!),我们假设字符串的开头是当前句子的开头(0)-我们在我们选择的索引之后做同样的事,除了如果索引之后没有句子结尾,我们分配str.length
let str=“Dana's places,有人来找我们,有人想买公寓。他们想快速搬家,我们失去了很多好地方。真的吗?”;
让GetSession=(ind,str)=>{
让beg、end、flag、SENTENDER=[“!”、“?”];
数组.from(str).forEach((c,c_索引)=>{
if(c_索引=ind&&sentencender.includes(c)){
结束=c_指数;
flag=true;
}
});
end=end | | str.length;
beg=beg | | 0;
返回str.slice(beg,end);
}
console.log(get句子(10,str));
console.log(GetSession(80,str))代码>索引如何与返回值关联?你是说如果索引在那个句子中,你只想返回那个句子吗?索引只是字符串中指定的位置,但我不一定要第一句或第二句。我想要指定字符的索引所在的句子。我还想分手吗?还有!