2009年06月06日

エンコードの変換

最近、(HandGrepで)エンコードの指定について色々やってみたので、
ついでに
標準入力をシフトJISに変換して標準出力に書き出すプログラムを作ってみた。
ソースは、UTF-8で記述。
コンパイルは、
>fsc conv.fs
(conv.fs だと何を変換するのかわかりにくいという向きには、ConvertEncoding.fs でもなんでもわかりやすい名前に)
想定している使用法:
ヘルプの表示
>conv /?
>conv --help

UTF-8 のファイルをシフトJISにする
>conv < index.rdf >index.txt
>type UTF8.txt | conv -encoding utf-8
EUC-JP のファイルをシフトJISにする
>conv -encoding euc < livedoor.html >livedoor_sjis.txt

以下はソース

//標準入力をシフトJISに変換して標準出力に書き出す

open System
open System.IO
open System.Text

let mutable encode = Encoding.UTF8
let SetEncoding (enc:string) = 
    try
      encode <-
      match enc.ToLower() with
      | "jis" -> Encoding.GetEncoding("iso-2022-jp")
      | enc when enc = "euc" or enc = "euc-jp" -> Encoding.GetEncoding(20932)
      | _  -> Encoding.GetEncoding(enc)
    with _ ->
      stderr.WriteLine("サポートされたエンコード名ではありません"); exit -1

[<STAThread()>]    
[<EntryPoint>]
let main(args) = 
    match args with
    | [|"-encoding"; enc |] ->
        SetEncoding enc // enc:{utf-8, sjis, iso-2022-jp, euc, euc-jp, ... }
    | [| option |] when option = "--help" or option = "/?" ->
        Console.WriteLine("conv [-encoding encode] //default UTF-8"); exit 0
    | _ -> ()

    let enc_bk = Console.InputEncoding
    Console.InputEncoding <- encode
    let mutable line:string = null
    while (line <- Console.ReadLine();line) <> null do
        Console.WriteLine(line)
    done
    Console.InputEncoding <- enc_bk

    0 //exit 0 でもOK

いちいちソースを挙げておく必要もないような気がしたが、
逆変換するdeconv.fs も挙げておく
//標準入力(sjis)を指定したエンコード(default:utf8)に変換して標準出力に書き出す

open System
open System.IO
open System.Text

let mutable encode = Encoding.UTF8
let SetEncoding (enc:string) = 
    try
      encode <-
      match enc.ToLower() with
      | "jis" -> Encoding.GetEncoding("iso-2022-jp")
      | enc when enc = "euc" or enc = "euc-jp" -> Encoding.GetEncoding(20932)
      | _  -> Encoding.GetEncoding(enc)
    with _ ->
      stderr.WriteLine("サポートされたエンコード名ではありません"); exit -1

[<STAThread()>]
[<EntryPoint>]
let main(args) =
    match args with
    | [|"-encoding"; enc |] ->
        SetEncoding enc // enc:{utf-8, sjis, iso-2022-jp, euc, euc-jp, ... }
    | [| option |] when option = "--help" or option = "/?" ->
        Console.WriteLine("deconv [-encoding encode] //default UTF-8"); exit 0
    | _ -> ()

    let enc_bk = Console.OutputEncoding
    Console.OutputEncoding <- encode
    let mutable line:string = null
    while (line <- Console.ReadLine();line) <> null do
        Console.WriteLine(line)
    done
    Console.OutputEncoding <- enc_bk

    0 //exit 0 でもOK

Posted by BLUEPIXY at 06:04│Comments(0)TrackBack(0)F# |

クリップコメント

トラックバックURL


pre表示(Firefox)

コメントする

名前
URL
 
  絵文字