2014-11-05 3 views
0

문장을 매개 변수로 사용하여 해당 문장을 단어 배열로 분할 한 다음 해당 단어 중 하나가 일치하는지 확인하는 루프를 만드는 코드를 만들려고합니다. 단어는 다른 배열에 있습니다.배열 오버랩 및 다른 배열 비교

아래 예에서 "ski"라는 단어가 포함 된 문장이 있습니다. 즉, 반환 값은 categories.type3이어야합니다.

어떻게 루프 검사를 할 수 있습니까? 서로 다른 범주간에 기능을 전환 할 수 있습니까? (예 : 단어가 action이 아닌 경우 adventure 등을 찾습니다.)

var categories = { 

    type1: "action", 
    type2: "adventure", 
    type3: "sport" 
} 

var Sentence = "This sentence contains the word ski"; 

var sport = ["soccer", "tennis", "Ski"]; 
var action = ["weapon", "explosions"]; 
var adventure = ["puzzle", "exploring"]; 

var myFreeFunc = function (Sentence) { 

    for (var i = 0; i < arrayLength; i++) { 

     if (typeArr[i] == word) { 

     } 
    } 
} 
+1

단어가 생각보다 분명하지 않을 수 있습니다. "산악 자전거"는 단어입니까? –

+0

물론 당신 말이 맞습니다. 이 시나리오에서 "산"과 "자전거"는 서로 다른 두 단어입니다. – Wranglerino

+0

[regex] (http://stackoverflow.com/tags/regex/info) 사용을 고려하셨습니까? – Goodword

답변

1

을 내가 코드를 다시 작성할 것 (당신은 항상해야 var 문을 결합하십시오.)

작은 숫자로 fiddle snippet을 추가했습니다. 예를 들어 데이터를 반복 할 수있는 방법을 설명합니다. 물론이 코드를 최적화하기 위해 다른 게시물을 체크 아웃해야합니다. (예 : 여러 공백에 대한 수정).

// make sure, your dictionary contains lower case words 
var categories = { 
    action: ["soccer", "tennis", "ski"], 
    adventure: ["weapon", "explosions"], 
    sport: ["puzzle", "exploring"] 
} 

var myFreeFunc = function myFreeFunc(Sentence) { 

    // iterates over all keys on the categories object 
    for (var key in categories) { 

     // convert the sentence to lower case and split it on spaces 
     var words = Sentence.toLowerCase().split(' '); 

     // iterates the positions of the words-array    
     for (var wordIdx in words) 
     { 
      // output debug infos 
      console.log('test:', words[wordIdx], categories[key], categories[key].indexOf(words[wordIdx]) != -1, '('+categories[key].indexOf(words[wordIdx])+')'); 

      // lets the array function 'indexOf' check for the word on position wordIdx in the words-array 
      if (categories[key].indexOf(words[wordIdx]) != -1) { 
       // output the found key 
       console.log('found', key); 

       // return the found key and stop searching by leaving the function 
       return key; 
      } 

     }//-for words 


    }//-for categories 

    // nothing found while iterating categories with all words 
    return null; 
} 

은 기능 부분 스 니펫을 제거했습니다 (주석 없음, 여분의 공백 없음, 콘솔 없음).) 로그 : 개체가 정말 재산 소유하는 경우

var myFreeFunc = function myFreeFunc(Sentence) { 
    for (var key in categories) { 
     var words = Sentence.toLowerCase().split(' ');   
     for (var wordIdx in words) 
     { 
      if (categories[key].indexOf(words[wordIdx]) != -1) { 
       return key; 
      } 
     } 
    } 
    return null; 
} 

  • 체크 코멘트에서 다루는 주제 누적 : 단어의 경계에 의해 obj.hasOwnProperty(prop)
  • 분할 문자열을 알니 타크에서 언급 한 바와 같이, (정규식 사용)/\ B/

니핏 일치위한 여러 카테고리 수집 g

  • :

    var myFreeFunc = function myFreeFunc(Sentence) { 
        var result = []; // collection of results. 
        for (var key in categories) { 
         if (categories.hasOwnProperty(key)) { // check if it really is an owned key 
          var words = Sentence.toLowerCase().split(/\b/g); // splitting on word bounds   
          for (var wordIdx in words) 
          { 
           if (categories[key].indexOf(words[wordIdx]) != -1) { 
            result.push(key); 
           } 
          } 
         } 
        } 
        return result; 
    } 
    
  • +0

    이 사진은 매우 멋지 며 실제로 이해할 수 있습니다. 그것의 대부분 =) – Wranglerino

    +1

    그것은 실제로 잘못되었습니다 - 배열을 반복하기 위해'for .. in'을 사용하고 있습니다. – Alnitak

    +0

    또한 둘 이상의 카테고리가 일치하는 경우 어떻게해야합니까? – Alnitak

    3

    어떤 범주가 문장과 일치하는지 알고 싶습니다.

    시작하려면 의미가없는 type1 등 식별자를 제거하고 고정 데이터를 필수 데이터를 직접 나타내는 개체, 특히 Map의 키/값 쌍으로 재 배열합니다. 각 키는 "카테고리"이름입니다 각 값은 해당 카테고리와 연관된 키워드 Set이다

    var categories = new Map([ 
        ['action', new Set(['weapon', 'explosions'])], 
        ['adventure', new Set(['puzzle', 'exploring'])], 
        ['sport', new Set(['soccer', 'tennis', 'ski'])] 
    ]); 
    

    [NB : SetMap ES6 새로운 기능이다. Polyfills은 available]

    이제 범주의 목록을 얻을 수있는 categories 맵을 반복 할 수있는 능력을 가지고 있고, 각 범주의 내용을 통해 핵심 단어를 찾을 :

    function getCategories(sentence) { 
        var result = new Set(); 
        var words = new Set(sentence.toLowerCase().split(/\b/g)); /* "/b" for word boundary */ 
        categories.forEach(function(wordset, category) { 
         wordset.forEach(function(word) { 
          if (words.has(word)) { 
           result.add(category); 
          } 
         }); 
        }); 
        return result.values(); // NB: Iterator interface 
    } 
    

    NB를 : 나는 ' 그것은 for .. of을 피할 수 없기 때문에 polyfill이 가능하지만, Set.prototype.forEachMap.prototype.forEach이 될 수 있습니다.

    function determineCategory(word){ 
    
        var dictionnary = { 
         // I assume here you don't need category1 and such 
    
         action: ["weapon", "explosions"], 
         aventure: ["puzzle", "exploring"], 
         sport: ["soccer", "tennis", "ski"] 
        } 
        var categories = Object.keys(dictionnary); 
        for(var i = 0; i<categories.length; i++){ 
         for(var j = 0; j<categories[i].length;j++){ 
          var wordCompared = dictionnary[categories[i]][j]; 
          if(wordCompared == word){ 
           return categories[i]; 
          } 
         } 
        } 
        return "not found"; 
    } 
    
    var sentence = "This sentence contains the word ski"; 
    var words = sentence.split(" "); // simple separation into words 
    var result = []; 
    for(var i=0; i<words.length; i++){ 
        result[i] = determineCategory(words[i]); 
    } 
    

    몇 가지 참고 사항을이 방법에 :

    +0

    이것은 재미 있고 완벽 해 보입니다. 나도 이걸 가지고 갈거야. 고맙습니다. – Wranglerino

    +0

    ECMAScript 6 (Map and Set) 접근 방식이 마음에 드네요. 대상 환경이 forEach 및 .has()뿐 아니라이를 지원하는지 확인하십시오. – BananaAcid

    +0

    @BananaAcid 따라서 polyfill ... – Alnitak

    0

    한 가지 간단한 방법은 다음과 같이 할 것

    는 기존의 구조를 변경할 필요가
    • (내가 알고하지 않습니다 그 가능)
    • 문장 분할 (공백 만 사용)은 그리 많이하지 않습니다. 더 영리한 접근 방법은 알 니탁의 대답을 보거나 토큰 화/lemmatization 방법을 찾아보십시오.
    • 당신에게 달려 단어가 바로 지금, 그냥 저장 (범주에 속하지 않는 경우 "을 (를) 찾을 수 없습니다"무엇을 결정하는 것입니다.