0
0

More than 3 years have passed since last update.

Ruby テキスト変換

Posted at

Ruby を使って PHP のプログラムを変換します。
PHPの文字コードは、EUC_JP と CP51932 が混在しています。
Python は、CP51932 を取り扱えないので、Ruby で記述しました。

str_src を str_target に置き換えます。
str_src がない時は、何もしません。

file_filter.rb
#! /usr/bin/ruby
# -*- coding: utf-8 -*-
#
#   file_filter.rb 
#
#                       Aug/09/2020
#
#
# --------------------------------------------------------------------
# [2]:
def read_proc(file_in)
    lines = []
    File.open(file_in) do |io|
        lines = io.readlines()
    end
#
    return lines
end
#
# --------------------------------------------------------------------
# [4]:
def convert_proc(lines)
    flag_convert = false
    str_src = '$var = $dict["aa"];'
    str_target = 'if(array_key_exists("aa",$dict)){$var = $dict["aa"];}'
    llx = str_src.size

    lines_new = []
    for line in lines do
        if line.slice(0,llx) == str_src then
            puts line
            lines_new.push(str_target)
            flag_convert = true
        else
            lines_new.push(line)
        end
#
end
#
    return flag_convert,lines_new

end
# --------------------------------------------------------------------
# [6]:
def out_proc(file_out,lines_new)
    File.open(file_out, mode = "w") do |f|
        lines_new.each{ |line| f.puts(line)}
    end
    STDERR.puts file_out + " written ***"
end
# --------------------------------------------------------------------
STDERR.puts "*** start ***"
file_in = ARGV[0]
#
lines = read_proc(file_in)
#
flag_convert,lines_new = convert_proc(lines)
#
if flag_convert then
    out_proc(file_in,lines_new)
end
#
STDERR.puts "*** end ***"
# --------------------------------------------------------------------

実行

./file_filter.rb in01.txt
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0