2012-12-12 7 views
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이 Ruby2는, Ruby3 하지만 내 코드가 작동하지 않습니다에 Ruby1, Ruby1, Ruby1를 교체합니다. 내 잘못은 어디에 있으며 어떻게 해결할 수 있습니까?문자열 int로 교체

를 들어

Ruby1 Ruby1 Ruby1

답변

0

text = File.read(filepath) 당신이 루프에서 반복해서 읽을 수 있도록 전체 파일을 읽고

Ruby1 Ruby2 Ruby3 교체 .

Idle for File.open,이 파일을 90 번 지울 수 있습니다. 당신은 오히려 오류 메시지가 어떻게되는지 설명해야

My code doesn't work. 

+0

코드는 작동하지만 희망하지 않습니다 – SemihY

+0

3 줄의 입력 파일을 제공하십시오. 더 이상의 정보 없이는 도움이되지 않습니다. – user1852994

+0

입력 파일 <섹션 ID = "bolum1"> <섹션 ID = "bolum1"> I 원하는 <섹션 ID = "bolum1"> <섹션 ID = "bolum2">에 – SemihY

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\">" 

이것이 올바른 해결책인지 확실치 않다. b. 나는 당신의 의견을 모른다. XML입니까? 적절한 XML 라이브러리를 사용하는 것이 더 좋을 수 있습니다. 더 복잡한가? 어쩌면 입력은 문법으로 파싱되어야합니다. www.antlr4.org 및 http://pragprog.com/book/tpantlr2/the-definitive-antlr-4-reference을 참조하십시오. 이 책의 소스 코드는 무료이며 XML 구문 분석을위한 문법을 ​​포함하고 있습니다.

희망이 있습니다. B