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を解析するための文法が含まれています。

お役に立てば幸いです。B

于 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 に答える