我在尝试将文本发送到某些拼写 API 时遇到一些问题。
API根据单词索引返回更正结果,例如:
句子:
"hello hoow are youu"
因此 API 按这样的数字对单词进行索引,并根据该索引返回更正:
0 1 2 3
hello hoow are youu
API 响应告诉我要更正哪些单词:
1: how
3: you
在代码中,我使用 split 命令将句子分解为单词数组,这样我就可以通过索引替换拼写错误的单词。
string.split(" ");
我的问题是,API 将单词之间的多个空格 trim 为一个空格,并且通过这样做,API 单词索引与我的索引不匹配。 (我想保留最终输出中的空格)
问题示例,单词之间有 4 个空格的句子:
Hello howw are youu?
0 1 2 3 4 5 6 7
hello hoow are youu
我考虑过循环单词数组并确定元素是单词还是空格,然后创建类似的新数组:
indexed_words[0] = hello
indexed_words[0_1] = space
indexed_words[0_2] = space
indexed_words[0_3] = space
indexed_words[0_4] = space
indexed_words[0_5] = space
indexed_words[0_6] = space
indexed_words[0_7] = space
indexed_words[1] = how
indexed_words[2] = are
indexed_words[3] = you?
这样我就可以轻松地替换拼写错误的单词,然后用 join 命令重建句子,但问题是我无法使用非数字索引(它混合了数组的顺序)
知道如何保留格式(空格)但仍然更正单词吗?
谢谢
最佳答案
在这种情况下,你有非常简单的解决方案:L
$(document).ready(function(){
var OriginalSentence="howw are you?"
var ModifiedSentence="";
var splitstring=OriginalSentence.split(' ')
$.each(splitstring,function(i,v){
if(v!="")
{
//pass this word to your api and appedn it to sentance
ModifiedSentence+=APIRETURNVALUE//api return corrected value;
}
else{
ModifiedSentence+=v;
}
});
alert(ModifiedSentence);
});
关于javascript - 按空格分割句子混淆了我的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40714747/