我正在搜索n-gram(大约100万行)的大型外部文件,以查找特定字符串的实例,并希望能够从该字符串出现的文件中返回整行。想知道这是否可能以及如何实现。 这是我目前的代码:
composeLines = function(importantWords, cb) {
var word = importantWords.shift();
fs.readFile("./w5_.txt", function(err, cont) {
if (err) throw err;
console.log("String"+(cont.indexOf(word)>-1 ? " " : " not ")+"found");
cb(importantWords);
});
};
使用此代码,我能够确定文件w5_.txt
是否包含一些很棒的字符串,但我需要能够获得它所属的n-gram。例如。搜索“design”会从文件中返回n-gram“设计的一部分”。
对此的任何帮助将不胜感激。
答案 0 :(得分:2)
一种选择是使用正则表达式:
// Make sure `word` is properly escaped first
// 'm' allows '^' and '$' to match line boundaries or
// start and beginning of the input (respectively)
var re = new RegExp('^.*' + word + '.*$', 'm');
var m = re.exec(cont);
if (m)
console.log('Word %j found on line: %j', word, m[0]);
else
console.log('Word %j not found', word);
答案 1 :(得分:0)
由于有数百万行,你应该以某种方式逐行阅读:
var word = importantWords.shift();
var matchCount = 0;
var lineCount = 0;
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream('file.in')
});
lineReader.on('line', function (line) {
lineCount++;
if(-1 < line.indexOf(word)){
console.log(line);
matchCount++;
}
});