gpt4 book ai didi

ruby - 如何根据位置将一些值写入ruby中的文本文件

转载 作者:太空宇宙 更新时间:2023-11-03 16:55:02 25 4
gpt4 key购买 nike

我需要一些帮助是一些独特的解决方案。我有一个文本文件,我必须在其中根据某个位置替换一些值。这不是一个大文件,并且在任何给定时间总是包含 5 行,所有行的长度都是固定的。但我必须只在某些位置专门替换 soem 文本。此外,我还可以在需要的位置输入一些文本,每次都用所需的值替换该文本。我不确定如何实现此解决方案。我在下面给出了示例。

Line 1 - 00000 This Is Me 12345 trying
Line 2 - 23456 This is line 2 987654
Line 3 - This is 345678 line 3 67890

请考虑以上是我必须用来替换某些值的文件。与第 1 行一样,我必须将“00000”替换为“11111”,而在第 2 行中,我必须将“This”替换为“Line”或任何需要四位数字的文本。该位置将始终在文本文件中保持不变。

我有一个可行的解决方案,但这是用于根据位置读取文件而不是用于写入。有人可以根据位置给出类似的解决方案吗

根据位置读取文件的解决方案:

def read_var file, line_nr, vbegin, vend 
IO.readlines(file)[line_nr][vbegin..vend]
end

puts read_var("read_var_from_file.txt", 0, 1, 3) #line 0, beginning at 1, ending at 3
#=>308

puts read_var("read_var_from_file.txt", 1, 3, 6)

#=>8522

我也尝试过这种写作解决方案。这可行,但我需要它基于位置或基于特定行中存在的文本工作。

探索写入文件的解决方案:

open(Dir.pwd + '/Files/Try.txt', 'w') { |f|
f << "Four score\n"
f << "and seven\n"
f << "years ago\n"
}

最佳答案

我给你做了一个工作样本 anagraj。

in_file = "in.txt"
out_file = "out.txt"

=begin
=>contents of file in.txt
00000 This Is Me 12345 trying
23456 This is line 2 987654
This is 345678 line 3 67890
=end

def replace_in_file in_file, out_file, shreds
File.open(out_file,"wb") do |file|
File.read(in_file).each_line.with_index do |line, index|
shreds.each do |shred|
if shred[:index]==index
line[shred[:begin]..shred[:end]]=shred[:replace]
end
end
file << line
end
end
end


shreds = [
{index:0, begin:0, end:4, replace:"11111"},
{index:1, begin:6, end:9, replace:"Line"}
]

replace_in_file in_file, out_file, shreds

=begin
=>contents of file out.txt
11111 This Is Me 12345 trying
23456 Line is line 2 987654
This is 345678 line 3 67890
=end

关于ruby - 如何根据位置将一些值写入ruby中的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12382956/

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