在我的机器人中,我实现了一个关键字过滤器,该机器人会在聊天记录中编写的每条消息中对其进行审阅,直到现在为止,它仍然有效,但是我想对其进行改进,出于尊重的考虑,我不会在此处添加任何文字,我再举一个例子,
机器人会检测您是否编写了例如“粗俗”,“错误”,“你好”
但是我要实现的是检测他们是否写了“ hellooo”,“ vuulgarr”,“ vulg4rr”
这是我存储单词的基础:
badwords.js
var words = ["vulgar", "vulg4r", "hello", "badword4", "badword5"]
module.exports = words;
这是我的函数,它使用indexOf()检查是否有坏词出现,拆分所有词,然后在找到结果后删除消息
index.js
const _ = require('lodash');
const badwords = require('./badwords');
/**
* Functions
*/
// compares every word to badWords array from badWords.js
function checkWord(word) {
return badwords.indexOf(word) > -1;
}
/**
* Main Module
*/
module.exports = function (self, nick, channel, message) {
'use strict';
message = message.toLowerCase();
message = message.split(' ');
nick = nick;
channel = channel.toLowerCase();
for (var i = 0, len = message.length; i < len; i++) {
if (checkWord(message[i])) {
self.send('.ban', channel, nick);
}
}
}
有任何改进的想法吗?,谢谢
答案 0 :(得分:0)
我们可以在两个字符串上使用两个指针进行比较,但是在重复时跳过偏移量:
function checkString(message, keyword) {
while(message.length > 0) {
if(checkPrefix(message, keyword)) return true
message = message.substr(1)
}
}
function checkPrefix(message, keyword) { // keyword is one of the keywords
let om = 0, ok = 0
while (true) {
if (ok >= keyword.length)
return true // we have finished reading keyword, and everything matched
if(om >= message.length)
return false // message is shorter than keyword
while (om + 1 < message.length && message.charAt(om) === message.charAt(om + 1))
om++ // skip consecutive repetitions in message
while (ok + 1 < keyword.length && keyword.charAt(ok) === keyword.charAt(ok + 1))
ok++ // skip consecutive repetitions in keyword
if (message.charAt(om) !== message.charAt(ok)) return false // encountered an inconsistent character
}
}
只需扫描字符串中的重复并首先将其删除。
function removeDuplicates(string) {
for (let i = 0; i < string.length - 1; ) {
if (string.charAt(i) === string.charAt(i + 1)) {
string = string.substr(0, i) + string.substr(i + 1) // skip string[i]
} else {
i++ // not duplicate, proceed to next pair
}
}
}
然后您可以直接进行比较:
removeDuplicates(message).indexOf(removeDuplicates(keyword)) !== -1
您可以这样应用它:
for (const part in message.split(" ")) {
for (word in words) {
if (removeDuplicates(part).indexOf(removeDuplicates(word)) !== -1)
self.send(".ban", ...)
break
}
}