我对Ruby很陌生,但对编程不是很熟悉。我只需要一个简单的脚本,给出一个文本文件,可以随意抽出大约10%的行。下面是我根据我编写的Python脚本得出的结果。为了让它更像Ruby,我需要做些什么呢?
prng = Random.new
File.open('english-words-partial.txt', 'w') { |f|
File.readlines('english-words-full.txt').each do |line|
if prng.rand >= 0.9
f.write(line)
end
end
}发布于 2014-07-03 04:11:32
这是我的机会:
File.open('english-words-partial.txt', 'w') do |file|
File.foreach('english-words-full.txt') do |line|
file.puts(line) if rand(10) == 0
end
end在Ruby中,可以在行尾添加一个if语句,以便有条件地执行该行。这也适用于works语句。
此外,rand函数可以接受一个数字,并从中产生那么多可能的数字。所以rand(10)会给出一个从0到9的随机数
在Ruby中,您通常希望对1行块使用{},对多行块使用do/end,但它们的作用略有不同。这里还有更多的内容:https://stackoverflow.com/questions/5587264/do-end-vs-curly-braces-for-blocks-in-ruby
File.foreach('...')比File.readlines('...').each稍短,更整洁(这要感谢@Flambino )。
最后,您可以在打印和but这样的文件对象上使用IO方法,所以我更喜欢这种方法,但是file.write也能工作。这是真正的个人偏好。
发布于 2014-07-04 13:59:39
这甚至更加随机(因为顺序会改变):
File.open('english-words-partial.txt', 'w') { |f|
full = File.readlines('english-words-full.txt')
f.puts full.sample(full.size/10)
end发布于 2014-07-13 18:05:26
下面是一种使用Array#sample方法和几个类方法来读取和写入IO类中定义的文本文件的方法。我所作的假设如下:
def doit(fname_in, fname_out, nbr)
n_lines = File.foreach(fname_in).reduce(0) { |c, _| c+1 }
return nil if n_lines.zero? || nbr.zero?
ndx = [*(0...n_lines)].sample(nbr).sort
f_out = File.open(FNAME_OUT, 'w')
offset = ndx.shift
File.foreach(fname_in).with_index do |line, i|
if i == offset
f_out.write(line)
offset = ndx.shift
end
break unless offset
end
f_out.close
endFNAME_IN, FNAME_OUT = 'infile', 'outfile'让我们首先创建一个输入文件:
lines =<<_
Now
is
the
time
for
all
good
Rubyists
to
put
aside
work
and
watch
the
World
Cup
final
between
Germany
and
Argentina
_
File.write(FNAME_IN, lines) #=> 116我们可以通过以下方式确认该文件的内容:
File.foreach(FNAME_IN) { |l| puts l }现在试一试:
doit(FNAME_IN, FNAME_OUT, 10)让我们看看是怎么写的。(滚筒辊.)
File.foreach(FNAME_OUT) { |l| puts l }
Now
is
the
for
to
aside
watch
World
Cup
finalhttps://codereview.stackexchange.com/questions/55946
复制相似问题