0
#! /usr/bin/env ruby

filepath = "chapter1.xhtml"
text = File.read(filepath)


i=1

text = File.read(filepath)

while i!=91


replace = text.gsub(/123123/) do |match|
  match=i.to_s()
end
File.open(filepath, "w") {|file| file.puts replace}
    i=i+1
end

我想将 Ruby1,Ruby1,Ruby1 替换为 Ruby1,Ruby2,Ruby3 但我的代码不起作用。我的错在哪里,我该如何解决?

例如

红宝石1 红宝石1 红宝石1

替换为

红宝石1 红宝石2 红宝石3

4

2 回答 2

0
input_path  = "chapter1.xhtml"
output_path = "new.txt"
#input = 'input file <section id="bolum1"> <section id="bolum1"> <section id="bolum1">'
string_to_replace = 'bolum1'
File.open(output_path, "w") do |output|
    File.open(input_path, 'r') do |f|
        f.readlines.each do |line|
            counter = 0
#            result = input.gsub(string_to_replace) do |match|
            result = line.gsub(string_to_replace) do |match|
#                puts "found=#{match}"
                counter += 1
                match[-1, 1] = counter.to_s # replace last char by counter
#                puts "replace=#{match}"
                match # the result of the block replaces the matched string
            end
            p result
            output.write(result)
        end
    end # input file will automatically be closed at the end of the block
end # output file will automatically be closed at the end of the block

文件 chapter1.xhtml :

input file <section id="bolum1"> <section id="bolum1"> <section id="bolum1">
input file <section id="bolum1"> <section id="bolum1"> <section id="bolum1">

执行 :

$ ruby -w t.rb 
"input file <section id=\"bolum1\"> <section id=\"bolum2\"> <section id=\"bolum3\">\n"
"input file <section id=\"bolum1\"> <section id=\"bolum2\"> <section id=\"bolum3\">"

我不确定这是正确的解决方案,因为我不知道您的意见。是 XML 吗?使用适当的 XML 库可能会更好。它更复杂吗?也许输入必须用语法解析。请参阅 www.antlr4.org 和http://pragprog.com/book/tpantlr2/the-definitive-antlr-4-reference。本书的源代码是免费的,并且包含解析 XML 的语法。

希望有帮助。乙

于 2012-12-14T16:15:59.437 回答
0

text = File.read(filepath)读取整个文件,因此您在循环中一次又一次地读取它。

同上File.open,您擦除文件 90 次。

My code doesn't work.

您应该解释发生了什么、错误消息等。

于 2012-12-12T19:31:15.017 回答