抓取文件中的随机行 [英] Grabbing a random line from file
本文介绍了抓取文件中的随机行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道该怎么做.我应该从哪里开始?我已经用谷歌搜索过,但没有一个关于如何从文本文件中拉出随机行的结果.
I have no idea on how to do this. Where should I start? I have googled this and not one result came up on how to pull a random line from a text file.
我唯一发现的是 https://github.com/chrisinajar/node-rand-a ,但是它不起作用.如何从文本文件中读取随机行?
The only thing I have found is https://github.com/chrisinajar/node-rand-line, however it doesn't work. How can I read a random line from a text file?
推荐答案
You would probably want to look at the node.js standard library function for reading files, fs.readFile, and end up with something along the lines of:
//note this will be async
function getRandomLine(filename, callback){
fs.readFile(filename, function(err, data){
if(err) {
throw err;
}
// note: this assumes `data` is a string - you may need
// to coerce it - see the comments for an approach
var lines = data.split('\n');
// choose one of the lines...
var line = lines[Math.floor(Math.random()*lines.length)]
// invoke the callback with our line
callback(line);
})
}
If reading the whole thing and splitting isn't an option, then maybe have a look at this stack overflow for ideas.
这篇关于抓取文件中的随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文