gpt4 book ai didi

ruby - 如何在 Ruby 中编辑 txtfile 中的每 x 行?

转载 作者:太空宇宙 更新时间:2023-11-03 17:32:44 24 4
gpt4 key购买 nike

我正在尝试使用 Ruby 更改文本文件中每隔一行的内容(有些文本文件我需要每三行更改一次,依此类推。)

我找到了 this question有助于遍历每一行,但我特别需要帮助每 x 行进行更改。

### 是我遇到问题的部分(迭代 x 行数。)

text = File.open('fr.txt').read
clean = ### .sub("\n", " ");
new = File.new("edit_fr.txt", "w")
new.puts clean
new.close

最佳答案

您可以如下使用模除法,其中 n 指的是您要处理的第 n 行,i 指的是文件行的从 0 开始的索引。使用这两个值,模数学提供整数除法的余数,只要基于 1 的索引 (i+1) 是 n 的倍数,余数将为 0。

n = 3 # modify every 3rd line

File.open('edit_fr.txt','w') do |f| # Open the output file
File.open('fr.txt').each_with_index do |line,i| # Open the input file
if (i+1) % n == 0 # Every nth line
f.print line.chomp # Remove newline
else # Every non-nth line
f.puts line # Print line
end
end
end

更多信息可在维基百科上找到:http://en.wikipedia.org/wiki/Modulo_operation

In computing, the modulo operation finds the remainder after division of one number by another (sometimes called modulus).

Given two positive numbers, a (the dividend) and n (the divisor), a modulo n (abbreviated as a mod n) is the remainder of the Euclidean division of a by n. For instance, the expression "5 mod 2" would evaluate to 1 because 5 divided by 2 leaves a quotient of 2 and a remainder of 1, while "9 mod 3" would evaluate to 0 because the division of 9 by 3 has a quotient of 3 and leaves a remainder of 0; there is nothing to subtract from 9 after multiplying 3 times 3. (Note that doing the division with a calculator will not show the result referred to here by this operation; the quotient will be expressed as a decimal fraction.)

关于ruby - 如何在 Ruby 中编辑 txtfile 中的每 x 行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29292867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com