- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在尝试使用 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/
我对此有点厌倦了。 我不知道为什么它一直告诉我文件未定义,因为它的声明和使用都在同一范围内。 var txtFile = ne
我正在尝试使用 Ruby 更改文本文件中每隔一行的内容(有些文本文件我需要每三行更改一次,依此类推。) 我找到了 this question有助于遍历每一行,但我特别需要帮助每 x 行进行更改。 ##
我是一名优秀的程序员,十分优秀!