gpt4 book ai didi

javascript - 在 JavaScript 中标记化

转载 作者:行者123 更新时间:2023-11-30 08:35:06 26 4
gpt4 key购买 nike

如果我有一个字符串,我如何将它拆分成一个单词数组并过滤掉一些停用词?我只想要长度为 2 或更大的单词。

如果我的字符串是

var text = "This is a short text about StackOverflow.";

我可以拆分它

var words = text.split(/\W+/);

但是使用split(/\W+/),我得到了所有的单词。我可以用

检查单词的长度是否至少为 2
function validate(token) {
return /\w{2,}/.test(token);
}

但我想我可以用正则表达式更聪明/更快地做到这一点。

我还有一个数组 var stopwords = ['has', 'have', ...] 数组中不应包含该数组。

实际上,如果我能找到一种方法来过滤掉停用词,我可以将所有字母 a、b、c、...、z 添加到停用词数组中,以仅接受至少包含 2 个字符的单词。

最佳答案

我会做你开始的事情:按 /W+/ 拆分,然后使用 .filter() 验证数组中的每个标记(长度和停用词) .

var text = "This is a short text about StackOverflow.";
var stopwords = ['this'];

var words = text.split(/\W+/).filter(function(token) {
token = token.toLowerCase();
return token.length >= 2 && stopwords.indexOf(token) == -1;
});

console.log(words); // ["is", "short", "text", "about", "StackOverflow"]

您可以轻松调整正则表达式来查找单词 >= 2 个字符,但如果您已经需要进行后处理以删除停用词 (token. length 将比您编写的任何花哨的正则表达式都快。

关于javascript - 在 JavaScript 中标记化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32188491/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com