请检查这把小提琴:https://jsfiddle.net/dp0y4hrw/16/
这是JS在字符串数组中查找最长的复合词。
而不是数组,我希望这个程序读取一个本地txt文件,包含100,000多行文本。然后找出最长的复合词。每一行都有一个词。
我尝试过使用FileReader来获取数据。我能够正确地传递数据,但是在“addPrefix”和“findPrefixes”之间的一些共享变量给我带来了麻烦。
我还尝试使用一种承诺来解释异步行为:
function readFile(event) {
var file = event.target.files[0];
if (file) {
new Promise(function(resolve, reject) {
var reader = new FileReader();
reader.onload = function (evt) {
resolve(evt.target.result);
};
reader.readAsText(file);
reader.onerror = reject;
})
.then(findLongestWord)
.catch(function(err) {
console.log(err)
});
}
}
document.getElementById('file').addEventListener('change', readFile, false);
function findLongestWord(data) {
...这仍然给了我一个问题。在这种情况下,读取文件的最佳方法是什么,这样我才能正确地处理内容?
编辑:
// adds word as a prefix
var addPrefix = function (word) {
var i = 0;
var current = prefixes;
var char;
while (char = word[i++]) {
if (!current[char]) {
current[char] = {};
}
current = current[char];
}
current.word = true;
return current.word; //RETURNING CURRENT WORD HERE
};
// Finds the longest prefix we can make using the word.
var findPrefixes = function (word) {
var prefix = '';
var current = prefixes;
var found = [];
var i = 0;
var char;
while (char = word[i++]) {
if (!current[char]) {
break;
}
// Move to the next character and add to the prefix.
current = current[char];
prefix += char;
if(current.word)
{
found.push(prefix);
}
}
return found;
};
//for each word in list, add to prefix
list.forEach(function (word) {
var prefix;
// If we can find a closest possible word, it may be possible to create a
// compound word - but we won't be able to check until we reach the end.
if ((prefix = findPrefixes(addPrefix())) && prefix.length) { //FINDPREFIXES USING ADDPREFIX HERE
prefixMatch.push([ word, prefix ]);
}
// Insert the word into the prefix tree.
addPrefix(word);
});编辑2:这是输入文本文件的示例:
cat
cats
catsdogcats
dog
dogcatsdog
hippopotamuses
rat
ratcatdogcat
catratdograt
dogcatscats预期结果是:最长:猫猫,猫猫.第二长:猫猫,复合词的dogcatscats...number :5
发布于 2016-09-19 05:43:41
使用RegExp /\w+/g
\w匹配基本拉丁字母中的任何字母数字字符,包括下划线。x+匹配前面的项目x1或更多次
var list = data.match(/\w+/g);https://stackoverflow.com/questions/39564937
复制相似问题