我正在搜索一个大型的 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。例如。搜索“设计”将从文件中返回 n-gram“设计的一部分”。
如有任何帮助,我们将不胜感激。
最佳答案
一种选择是使用正则表达式:
// 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);
关于javascript - 使用 Node.js 的 fs.readFile() 返回出现字符串的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36414187/