0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Python] 全角文字を半角文字へ変換する

Last updated at Posted at 2025-04-07

コード

import functools
import re

def bytesToInt(b):
  return int(b.hex(), 16)

def intToBytes(i):
  return bytes.fromhex(f"{i:x}")

def getDiff(c1, c2):
  e1 = c1.encode()
  e2 = c2.encode()
  return bytesToInt(e1) - bytesToInt(e2)

def exchange(match, diff):
  r = bytesToInt(match[0].encode()) - diff
  return intToBytes(r).decode()

exchange1 = functools.partial(exchange, diff=0xEFBC60)
exchange2 = functools.partial(exchange, diff=0xEFBD20)

def wideStringToHalfString(c):
  pat1 = re.compile("[!-/0-9:-@A-Z[-_]")
  pat2 = re.compile("[a-z`{-~]")
  t = pat1.sub(exchange1, c)
  return pat2.sub(exchange2, t)

if __name__ == "__main__":
  data = [
    "!"#$%&'()*+,-./",
    "0123456789",
    ":;<=>?@",
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
    "[\]^_",
    "abcdefghijklmnopqrstuvwxyz",
    "`{|}~",
  ]

  print(f"{getDiff('', '!'):X}")
  print(f"{getDiff('', '0'):X}")
  print(f"{getDiff('', ':'):X}")
  print(f"{getDiff('', 'A'):X}")
  print(f"{getDiff('', '['):X}")
  print(f"{getDiff('_', '_'):X}")
  print(f"{getDiff('', 'a'):X}")
  print(f"{getDiff('', '`'):X}")  # 並びがおかしい?
  print(f"{getDiff('', '{'):X}")

  print("".join(data))
  r = wideStringToHalfString("".join(data))
  print(r)
0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?