按空格分割句子混淆了我的索引

时间:2016-11-21 07:19:59

标签: javascript jquery

我在尝试将文本发送到某些拼写API时遇到了一些问题。

API会根据单词index返回更正,例如:

句子:

  

“hello hoow are youu”

因此,API会按照这样的数字对单词进行索引,并根据该索引返回更正:

  0     1   2   3
hello hoow are youu

API响应,告诉我要纠正哪些词:

1: how
3: you

在代码中我使用split命令将句子分解为单词数组,这样我就可以用它们的索引替换拼写错误的单词。

string.split(" ");

我的问题是API将单词之间的多个空格修剪为一个空格,并且通过这样做,API单词索引与我的索引不匹配。 (我想保留最终输出的空格)

问题的例子,单词之间有4个空格的句子:

  

你好,你好吗?

      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命令重新生成句子,但问题是我不能使用非数字索引的问题(它混合了数组的顺序)

知道如何保持格式(空格)但仍然纠正单词?

由于

4 个答案:

答案 0 :(得分:0)

<强>更新

var str = "Hello      howw are youu?";

var words = str.split(" "); 

// Getting an array without spaces/empty values
// send it to your API call
var requestArray = words.filter(function(word){
    if (word) {
        return word;
    }
});


console.log("\nAPI Response that tell me which words to correct:");
console.log("6: how\n8: you");

var response = {
  "1": "how",
  "3": "you"
}

//As you have corrected words index, Replace those words in your "requestArray"
for (var key in response) {
    requestArray[key] = response[key];
}

//now we have array of non-empty & correct spelled words. we need to put back empty (space's) value back in between this array 
var count = 0;
words.forEach(function(word, index){
    if (word) {
        words[index] = requestArray[count];
        count++;
    }
})

console.log(words);

如果我错了,请纠正我。

希望这会有所帮助:)

答案 1 :(得分:0)

请查看以下内容: 对于像这样的字符串操作,我强烈建议您使用Regex 使用在线正则表达式编辑器可以更快地尝试和错误https://regex101.com/。 在这里我使用/ \ w + / g来match每个单词,如果你想忽略一两个单词,我们可以使用/\w{2,}/g或类似的东西。

var str = "Hello      howw are youu?";
var re = /\w+/g
var words = str.match(re); 
console.log("Returning valus")
words.forEach(function(word, index) {
  console.log(index + " -> " + word);
})

<强>校正

请注意,您需要保持间距,请尝试以下方法: 我使用您的方法将所有更改为space。为其修改版本创建数组然后发送到您的API(我不知道那部分)。然后从API返回数据,将其重新转换回其原始格式化字符串。

var ori = `asdkhaskd asdkjaskdjaksjd     askdjaksdjalsd a  ksjdhaksjdhasd    asdjkhaskdas`;

function replaceMeArr(str, match, replace) {
  var s = str,
    reg = match || /\s/g,
    rep = replace || ` space `;
  return s.replace(reg, rep).split(/\s/g);
}

function replaceMeStr(arr, match, replace) {
  var a = arr.join(" "),
    reg = match || /\sspace\s/g,
    rep = replace || " ";
  return a.replace(reg, rep);
}

console.log(`ori1: ${ori}`);
//can use it like this 
var modified = replaceMeArr(ori);
console.log(`modi: ${modified.join(' ')}`);

//put it back
var original = replaceMeStr(modified);
console.log(`ori2: ${original}`);

答案 2 :(得分:0)

在这种情况下,你有一个非常简单的解决方案: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);


     });

答案 3 :(得分:0)

Try this JSFiddle ,快乐编码:)

&#13;
&#13;
//
//  ReplaceMisspelledWords
//
//  Created by Hilal Baig on 21/11/16.
//  Copyright © 2016 Baigapps. All rights reserved.
//

var preservedArray = new Array();
var splitArray = new Array();

/*Word Object to preserve my misspeled words indexes*/
function preservedObject(pIndex, nIndex, title) {
  this.originalIndex = pIndex;
  this.apiIndex = nIndex;
  this.title = title;
}

/*Preserving misspeled words indexes in preservedArray*/
function savePreserveIndexes(str) {
  splitArray = str.split(" ");
  //console.log(splitArray);
  var x = 0;
  for (var i = 0; i < splitArray.length; i++) {
    if (splitArray[i].length > 0) {
      var word = new preservedObject(i, x, splitArray[i]);
      preservedArray.push(word);
      x++;
    }
  }
};


function replaceMisspelled(resp) {
  for (var key in resp) {

    for (var i = 0; i < preservedArray.length; i++) {
      wObj = preservedArray[i];
      if (wObj.apiIndex == key) {
        wObj.title = resp[key];

        splitArray[wObj.originalIndex] = resp[key];

      }
    }
  }

  //console.log(preservedArray);
  return correctedSentence = splitArray.join(" ");
}

/*Your input string to be corrected*/
str = "Hello      howw are youu";
console.log(str);
savePreserveIndexes(str);
/*API Response in json of corrected words*/
var apiResponse = '{"1":"how","3":"you" }';
resp = JSON.parse(apiResponse);

//console.log(resp);
/*Replace misspelled words by corrected*/
console.log(replaceMisspelled(resp)); //Your solution
&#13;
&#13;
&#13;