您的位置:首页 > 其它

如何在100万文字的文章中 200ms内 快速提取 替换 上万个关键字

2017-03-17 10:00 316 查看

关键点:

 

  关键字 组合 成一棵 hash 树  ( 有属性就直接移动指针到下一个字对象, 没有属性就创建子对象, 再移动指针;  第二次循环在子对象看有没这个属性 )

 

  探测针       标记结束         跳跃      回溯

 

var treeSearch = {
makeTree: function(strKeys) {
"use strict";

var tblCur = {},
tblRoot,
key,
str_key,
Length,
j,
i
;
tblRoot = tblCur;

for ( j = strKeys.length - 1; j >= 0; j -= 1) {

str_key = strKeys[j];
Length = str_key.length;

for ( i = 0; i < Length; i += 1) {

key = str_key.charAt(i);
if (tblCur.hasOwnProperty(key)) { //生成子节点
tblCur = tblCur[key];
} else {
//在当前的对象 创建一个子对象
tblCur[key] = {}

//移动当前指针到 这个新的子对象
tblCur = tblCur[key];

}
}

tblCur.end = true; //最后一个关键字没有分割符

tblCur = tblRoot;
}

return tblRoot;
},

search: function(content, tblRoot) {
"use strict";
var tblCur,
p_star = 0,
n = content.length,
p_end,
match,  //是否找到匹配
match_key,
match_str,
arrMatch = [],  //存储结果
arrLength = 0   //arrMatch的长度索引
;

while (p_star < n) {
/*
tblRoot { a:{ b: {c: {end:true}, d: {end: true }  } },  { }   }

n : 10000
*/
tblCur = tblRoot; //回溯至根部
p_end = p_star;
match_str = "";
match = false;

do {

/* UCOKsfKBdaqRYQqSYUYjdvDR
match_key :  U
*/
match_key = content.charAt(p_end);

if (!(tblCur = tblCur[match_key])) { // (向前移动) tblCur指针, 指向下一个 深层子对象

p_star += 1;   // 确认安全后, 小不点 p_start 移动一个位置

break;    //直接进入到下一次循环  ---->  out
}

match_str += match_key;  //保存  [match]

p_end += 1;              // p_star 小不点,  p_end 小不点的探测器 (向前移动)

if (tblCur.end === true) { //
match = true;          //说明这几个木板下有坑
}

} while (true);

if (match === true) { //最大匹配

/**
把找到的 标记起来
**/
arrMatch[arrLength] = { //增强可读性
key: match_str,
begin: p_star - 1,
end: p_end
};
arrLength += 1;

p_star = p_end;   // 小不点直接跳过坑
}

}
return arrMatch;
}
}

function test(strContent, strKeys) {
var arrMatch,
tblRoot = treeSearch.makeTree(strKeys),
t = new Date();

arrMatch = treeSearch.search(strContent, tblRoot);

console.log("time is: " + (new Date() - t) + "mm");

console.dir(arrMatch[0]);
}

var s = "abcd汉能abcd"; /*(function() {
var Things = [' ', '\n', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
var s = "";

for (var i = 1000000; i >= 0; i--) {
s += Things[parseInt(Math.random() * Things.length) % Things.length]
};

return s;

})()*/

test(s, ["汉能",  "abd"]);
View Code

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: