从句子中删除停用词

时间:2017-08-08 06:29:50

标签: javascript json regex reactjs stop-words

我有一个句子,但这个句子在每个空格都是分开的。

我的数据输出如下

const escapeRE = new RegExp(/([/\?""])/g);
const myDatas = data.map(des => des.Sentence.toLowerCase().replace(escapeRE, '').split(' '));

[ [ 'yes',
'keep',
'go',
'apple',
'tabacco',
'javascript',
'no',
'uhh',
'omg',
'hi.' ],
['say',
'hello',
'me',
'allright',
'maybe',
'mi',
'say.' 
....] ]

而且我有一个停用词JSON文件。

停用词JSON文件

的内容
['yes',
'hi',
'so',
'say',
'me',
'uhh',
'omg',
'go',
'hello',
'hi' 
 ...]

所以我想从数组句子中删除停用词。 我想要纯粹的句子,没有停止的话。 stopwords定义;

const stopwords = require('./stop_words.json');

那我该怎么办?我什么都不知道。我试过myDatas.replace('stopwords', '' )函数,但它没用了

4 个答案:

答案 0 :(得分:1)

您可以使用这样的数组原型:

Array.prototype.diff = function(stopwords) {
    return this.filter(function(word) {
        var punctuationlessWord = word.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "");
        return stopwords.indexOf(punctuationlessWord) < 0;
    });
};

用法:

myDatas.forEach(function(part, index, theArray) {
  theArray[index] = theArray[index].diff( stopwords );
});

var myDatas = [ [ 'yes',
'keep',
'go',
'apple',
'tabacco',
'javascript',
'no',
'uhh',
'omg',
'hi.' ],
['say',
'hello',
'me',
'allright',
'maybe',
'mi',
'say.'] ];

var stopwords = ['yes',
'hi',
'so',
'say',
'me',
'uhh',
'omg',
'go',
'hello',
'hi'];

Array.prototype.diff = function(stopwords) {
    return this.filter(function(word) {
		var punctuationlessWord = word.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"");
		return stopwords.indexOf(punctuationlessWord) < 0;
	});
};

myDatas.forEach(function(part, index, theArray) {
  theArray[index] = theArray[index].diff( stopwords );
});

console.log(myDatas);

答案 1 :(得分:0)

您可以使用jQuery grep函数实现目标。你可以使用如下。

    var withoutStopWords = jQuery.grep(myDatas, function(element, index){
  return stopwords.indexOf(element)<0;
                  });

Javascript示例

var filtered=myDatas.filter(function(e){return this.indexOf(e)<0;},stopwords);

答案 2 :(得分:0)

我想到的第一条大腿就是你可以创建递归函数来迭代句子数组,然后检查句子单词是否在stopWords数组中,如下所示:

function removeStopWords(sentenceArray, stopWords, result = []) {
    sentenceArray.forEach((sentence) => {
        if (Array.isArray(sentence)) {
            result = removeStopWords(sentence, stopWords, result);
        } else if (!stopWords.includes(sentence)) {
            result = result.concat(sentence)
        }
    });

    return result;
}

答案 3 :(得分:0)

这是ES6 solitions

null
相关问题