Lightweight Language Lovers

PythonとRubyを比較してみる(Pythonによるコーディング)

#format 
class SjisChars
  
  $KCODE = "SJIS"
  KU13 = 0x8740..0x879c
  KU89_92 = 0xED40..0xEEFC
  KU115_9 = 0xFA40..0xFC4B
  GAIJI = 0xF040..0xF9FC
  
  def initialize(chars)
    @chars = chars
    @reKisyu = mkRegexp(KU13, KU89_92, KU115_9)
    @reGaiji = mkRegexp(GAIJI)
  end
  
  def mkRegexp(*ra)
    ra.map! {|r| "[%s-%s]" % [[r.first].pack("n"), [r.last].pack("n")]}
    Regexp.compile(ra.join("|"))
  end
  
  def scanSjis
    @chars.split(//).each {|c| yield c, isKanji(c), isGaiji(c), isKisyu(c)}
  end
  
  def isKanji(c)
    c.length == 2
  end
  
  def isGaiji(c)
    @reGaiji.match(c) != nil
  end
  
  def isKisyu(c)
    @reKisyu.match(c) != nil
  end
  
  def hexprint
    scanSjis do |c, isKanji, isGaiji, isKisyu|
      h = (c.unpack("n")[0] if isKanji) || c.unpack("C")[0]
      attr = ("Gaiji" if isGaiji) || ("Kisyu" if isKisyu) || ""
      printf("%s %x %s\n", c, h, attr)
    end
  end
      
end
  
sc = SjisChars.new("abc漢字・・①㈱纊彧德羽裵錞德鍈ⅰ黑")
sc.hexprint
sc.scanSjis do |c, k, g, ki|
  printf("%s %s %s %s\n", c, k, g, ki)
end

  
  


CategoryPython CategoryRuby