어떤 범주가 문장과 일치하는지 알고 싶습니다.
시작하려면 의미가없는 type1
등 식별자를 제거하고 고정 데이터를 필수 데이터를 직접 나타내는 개체, 특히 Map
의 키/값 쌍으로 재 배열합니다. 각 키는 "카테고리"이름입니다 각 값은 해당 카테고리와 연관된 키워드 Set
이다
var categories = new Map([
['action', new Set(['weapon', 'explosions'])],
['adventure', new Set(['puzzle', 'exploring'])],
['sport', new Set(['soccer', 'tennis', 'ski'])]
]);
[NB : Set
및 Map
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.forEach
과 Map.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]);
}
몇 가지 참고 사항을이 방법에 :
단어가 생각보다 분명하지 않을 수 있습니다. "산악 자전거"는 단어입니까? –
물론 당신 말이 맞습니다. 이 시나리오에서 "산"과 "자전거"는 서로 다른 두 단어입니다. – Wranglerino
[regex] (http://stackoverflow.com/tags/regex/info) 사용을 고려하셨습니까? – Goodword