2016-03-31 43 views
0

我有一個字符串列表,我要檢查如果字符串包含特定的詞,如果它不分裂的所有單詞串並把它添加到一個關聯數組。字符串分割爲一個多維數組

myString = ['RT @Arsenal: Waiting for the international', 'We’re hungry for revenge @_nachomonreal on Saturday\'s match and aiming for a strong finish'] 

wordtoFind = ['@Arsenal']  

我想通過wordtoFind循環,如果是在myString,分裂myString爲單個單詞,並創建一個對象,像

newWord = {@Arsenal:[{RT:1},{Waiting:1},{for:1},{the:1},{international:1}]} 

for(z=0; z <wordtoFind.length; z++){ 
    for (i = 0 ; i < myString.length; i++) { 
    if (myString[i].indexOf(wordtoFind[z].key) > -1){ 
     myString[i].split(" ") 
    } 
    } 
} 
+3

你的newWord不是一個有效的對象。 –

+0

你能澄清嗎?我不明白你想要創建什麼。實際上,該客體是無效的(什麼鍵或{等待:1},{爲:1}等 你希望所有的話到像對象?{字:1}你能解釋 – Vincent

+0

所以呢?要統計每個單詞在你的字符串? – PostCrafter

回答

0

你在正確的軌道上。您只需將拆分字符串存儲到關聯數組變量中。

var assocArr = []; 
for(z=0; z <wordtoFind.length; z++){ 
    for (i = 0 ; i < myString.length; i++) { 
     if (myString[i].indexOf(wordtoFind[z]) > -1){ 

      myString[i].split(" ").forEach(function(word){ 
       assocArr.push(word); 
      }); 

     } 
    } 
} 
+0

的。關鍵是不工作的if語句 - 這樣使用它:\t \t如果(MyString的[I] .indexOf(wordtoFind [Z])> -1){.... 。 – mikesp

+0

謝謝。這就是我得到的粘貼複製我猜:/ – senschen

2

我會說喜歡的東西會起作用,這也算一個單詞在一個句子中出現的次數。例如,JavaScript沒有像PHP這樣的關聯數組。他們只是objects或編號arrays

var myString = ['RT @Arsenal: Waiting for the international', 'We’re hungry for revenge @_nachomonreal on Saturday\'s match and aiming for a strong finish']; 

var wordtoFind = ['@Arsenal']; 

var result = {}; 

for(var i = 0, l = wordtoFind.length; i < l; i++) { 

    for(var ii = 0, ll = myString.length; ii < ll; ii++) { 
     if(myString[ii].indexOf(wordtoFind[i]) !== -1) { 
      var split = myString[ii].split(' '); 
      var resultpart = {}; 
      for(var iii = 0, lll = split.length; iii < lll; iii++) { 
       if(split[iii] !== wordtoFind[i]) { 
        if(!resultpart.hasOwnProperty(split[iii])) { 
         resultpart[split[iii]] = 0; 
        } 
        resultpart[split[iii]]++; 
       } 
      } 
      result[wordtoFind[i]] = resultpart; 
     } 
    } 
} 

console.log(result); 
//{"@Arsenal":{"RT":1,"Waiting":1,"for":1,"the":1,"international":1}} 
+0

感謝這一點,但我得到了一個評論說,結果不是一個有效的對象。我現在編輯了這個問題,這將如何改變答案?謝謝@PierreDuc –

+0

@qwertyayyy有沒有理由讓它成爲一個數組?我的答案也會生成一個有效的對象。如果你檢查'console.log'的輸出,你可以看到它是什麼。它會改變我的答案,使它更難(但並非不可能)計算出現次數 – PierreDuc

+0

@PierreDuuc對不起,我是Javascript的新手,我剛剛收到一條評論,說這是一個無效的對象。但是,謝謝你的回答 –

0

我認爲,堅持你的關鍵問題是數據結構。最佳的結構應該是這樣的:

{ 
    @Arsenal:[ 
     {RT:1, Waiting:1, for:1, the:1, international:1}, 
     {xxx:1, yyy:1, zzz:3}, //for there are multiple ones in 'myString' that contain the same '@Arsenal' 
     {slkj:1, sldjfl:2, lsdkjf:1} //maybe more 
    ] 
    someOtherWord:[ 
     {}, 
     {}, 
     .... 
    ] 
} 

,代碼:

var result = {}; 

//This function will return an object like {RT:1, Waiting:1, for:1, the:1, international:1}. 
function calculateCount(string, key) { 
    var wordCounts = {}; 
    string.split(" ").forEach(function (word) { 
     if (word !== key) { 
      if (wordCounts[word] === undefined) wordCounts[word] = 1; 
      else wordCounts[word]++; 
     } 
    }); 
    return wordCounts; 
} 

//For each 'word to find' and each string that contain the 'word to find', push in that returned object {RT:1, Waiting:1, for:1, the:1, international:1}. 
wordToFind.forEach(function (word) { 
    var current = result[word] = []; 
    myString.forEach(function (str) { 
     if (str.indexOf(word) > -1) { 
      current.push(
       calculateCount(str, word) 
      ); 
     } 
    }); //Missed the right parenthesis here 
}); 
+0

嗨我收到語句「繼續」的語法錯誤@ Yan-Yang –

+0

@qwertyayyy對不起。我犯了一個錯誤。我修改了代碼,現在可以。 '繼續'不能在'forEach'中使用。這裏有一個關於這個問題:http://stackoverflow.com/questions/31016841/using-break-and-continue-in-each-and-foreach –

+0

不好意思,但我怎麼輸出這個控制檯。它只是返回一個空的列表。 @ Yan-Yang –

1

這種方法利用的forEach - 函數和回調。 containsWord函數爲了減少一些回調而留下了一個for循環,這顯然可以改變。

var myString = [ 
    'RT @Arsenal: Waiting for the international', 
    'We’re hungry for revenge @_nachomonreal on Saturday\'s match and aiming for a strong finish', 
    '@Arsenal: one two three four two four three four three four' 
]; 

var wordtoFind = ['@Arsenal']; 

// define the preprocessor that is used before the equality check 
function preprocessor(word) { 
    return word.replace(':', ''); 
} 

function findOccurences(array, search, callback, preprocessor) { 
    var result = {}; 
    var count = 0; 
    // calculate the maximum iterations 
    var max = search.length * array.length; 
    // iterate the search strings that should be matched 
    search.forEach(function(needle) { 
     // iterate the array of strings that should be searched in 
     array.forEach(function(haystack) { 
      if (containsWord(haystack, needle, preprocessor)) { 
       var words = haystack.split(' '); 
       // iterate every word to count the occurences and write them to the result 
       words.forEach(function(word) { 
        countOccurence(result, needle, word); 
       }) 
      } 
      count++; 
      // once every iteration finished, call the callback 
      if (count == max) { 
       callback && callback(result); 
      } 
     }); 
    }); 
} 

function containsWord(haystack, needle, preprocessor) { 
    var words = haystack.split(' '); 
    for (var i = 0; i < words.length; i++) { 
     var word = words[i]; 
     // preprocess a word before it's compared 
     if (preprocessor) { 
      word = preprocessor(word); 
     } 
     // if it matches return true 
     if (word === needle) { 
      return true; 
     } 
    } 
    return false; 
} 

function countOccurence(result, key, word) { 
    // add array to object if it doesn't exist yet 
    if (!result.hasOwnProperty(key)) { 
     result[key] = []; 
    } 
    var entry = result[key]; 
    // set the count to 0 if it doesn't exist yet 
    if (!entry.hasOwnProperty(word)) { 
     entry[word] = 0; 
    } 
    entry[word]++; 
} 

// call our function to find the occurences 
findOccurences(myString, wordtoFind, function(result) { 
    // do something with the result 
    console.log(result); 
}, preprocessor); 

// output: 
/* 
{ '@Arsenal': 
    [ RT: 1, 
    '@Arsenal:': 2, 
    Waiting: 1, 
    for: 1, 
    the: 1, 
    international: 1, 
    one: 1, 
    two: 2, 
    three: 3, 
    four: 4 ] } 
*/ 

如果答案需要澄清,可隨時提出任何問題。

我希望這適合您的需求。

+0

你把它帶到下一個層次;)。但是有一點說,'forEach'不是'異步'功能。 – PierreDuc

+1

@PierreDuc是正確的,我最近沒有使用過多,顯然阻塞了。也感謝編輯英文文檔,甚至沒有注意到谷歌引導我到德文版本。 ;) – PostCrafter