March 01, 2005

[Ruby] 半角かな変換

Rubyで普通のカタカナをJIS X 0201カタカナ(半角カナ)に変換します。
もともとの文字コードは何でもいいと思います。
仕事で必要だったので作りました。

以下、コード。

# Copyright (c) 2005, Mellowtone Inc., ARAI Shunichi
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer. 
# Neither the name of the Mellowtone Inc. nor the names of its contributors may
# be used to endorse or promote products derived from this software without
# specific prior written permission. 

require 'jcode'

# detach dakuten/handakuten marks from composite katakana characters.
# also substitute some characters which are not supported in JIS X 0201.

def kanabreak(str)
	daku = "ガギグゲゴザジズゼゾダヂヅデドバビブベボヴ"
	daku2 = "カキクケコサシスセソタチツテトハヒフヘホウ"
	handaku = "パピプペポ"
	handaku2 = "ハヒフヘホ"

	str.gsub!(/[#{daku}]/) {|c| c + "゛"}
	str.gsub!(/[#{handaku}]/) {|c| c + "゜"}
	str.tr!(daku,daku2)
	str.tr!(handaku,handaku2)
	str.tr!("ヵヶヰヱヮ","カケイエワ")
	return str
end

# convert Japanese katakana characters to JIS X 0201 format.

def kanazenhan(str)
	str = kanabreak(str)
	zenkana = "。「」、・ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゛゜"
	a = zenkana.split(//)
	kanahash = {}
	a.each_index {|i| kanahash[a[i]] = i + 0xA1 }
	str.gsub!(/[#{zenkana}]/) { |c| kanahash[c].chr }
	return str
end

def test

test = <<TEST
「テストデース、アライ・シュンイチ。」
ァアィイゥウェエォオ カ ガ キ ギ ク
グ ケ ゲ コ ゴ サ ザ シ ジ ス ズ セ ゼ ソ ゾ タ
ダ チ ヂ ッ ツ ヅ テ デ ト ド ナ ニ ヌ ネ ノ ハ
バ パ ヒ ビ ピ フ ブ プ ヘ ベ ペ ホ ボ ポ マ ミ
ム メ モ ャ ヤ ュ ユ ョ ヨ ラ リ ル レ ロ ヮ ワ
ヰ ヱ ヲ ン ヴ ヵ ヶ
TEST

	puts kanabreak(test)
	puts kanazenhan(test)
end
Posted by arai at March 1, 2005 12:19 AM
Comments
Post a comment














Please enter this 6digits Security Code (for SPAM's sake...).
spam対策のため6桁のセキュリティコードを入力してください。