大佬教程收集整理的这篇文章主要介绍了使用 Ruby 在文件中正确组合单词,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个充满单词的文件,我正在尝试编写一个脚本,该脚本基本上可以将 2 个单词的每个组合从该列表转换到另一个列表。
require 'tempfile'
require 'fileutils'
path = 'Lst.lst'
temp_file = Tempfile.new('lst2.lst')
begin
file.open(path,'r') do |file|
file.readlines(filE).each do |line|
file.each_line do |baseline|
temp_file.puts line.gsub("\n",'') + baseline
end
end
end
temp_file.close
fileUtils.mv(temp_file.path,'lst2.lst')
ensure
temp_file.close
temp_file.unlink
end
脚本运行但外循环只运行一次。我该如何解决这个问题?
一般来说,Ruby 中的显式循环不是惯用的,尽管总有例外。您通常会发现使用对象的本机迭代器更容易执行您想要的操作。
给定一个像 word_list.txt 这样的文件,其中包含一小组这样的内容:
a
b
c
d
e
f
g
您可以使用 Array#combination 进行配对组合。例如,使用 Ruby 3.0.0:
words = File.readlines('word_list.txt').map &:chomp
word_pairs = words.combination 2
File.open('new_list.txt','w') do |file|
word_pairs.map { file.puts "#{_1}\t#{_2}" }
end
然后您可以在 sHell 中验证您的输出结果:
$ cat new_list.txt
a b
a c
a d
a e
a f
a g
b c
b d
b e
b f
b g
c d
c e
c f
c g
d e
d f
d g
e f
e g
f g
以上是大佬教程为你收集整理的使用 Ruby 在文件中正确组合单词全部内容,希望文章能够帮你解决使用 Ruby 在文件中正确组合单词所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。