LoginSignup
0
0

小道具: ASCII/数字/アルファベットの全角文字を半角文字に変換

Last updated at Posted at 2024-04-28

Qiita CLI 向けです。

Qiita の編集画面で全角のアルファベットが注意されるようになっていたので、全角(ASCII/数字/アルファベット)を半角にするものを作ってみました。(探せば良いツールがあるでしょうけど…)

コマンド ラインで変換したいファイル(複数:UTF-8のみ)を指定すると

  • 入力ファイル: file.ext
  • 出力ファイル: file.f2h.ext

として変換します。変換不要な場合はスキップします。

#!/usr/bin/env python3

import argparse
import os
import sys

parser = argparse.ArgumentParser()
parser.add_argument('-A', '--ascii', action='store_true', help='ASCII文字を半角化')
parser.add_argument('-a', '--alphabet', action='store_true', help='アルファベットを半角化')
parser.add_argument('-n', '--number', action='store_true', help='数字を半角化')
parser.add_argument('-f', '--force', action='store_true', help='強制出力')
parser.add_argument('-q', '--quiet', action='store_true', help='静寂モード')
parser.add_argument('files', metavar='FILE', nargs='+')
args = parser.parse_args()

TABLE = {
    chr(c+0xfee0): chr(c) for f, (s, n) in (
        (args.ascii, (0x21, 94)),
        (args.number, (0x30, 10)),
        (args.alphabet, (0x41, 26)), (args.alphabet, (0x61, 26)),
    ) if f for c in range(s, s+n)
}

if not TABLE:
    parser.print_help()
    print('\n変換する文字種を指定してください。\n')
    sys.exit(1)

for ifile in args.files:
    with open(ifile, 'r') as fp:
        idata = fp.read()
    odata = ''.join(map(lambda c: TABLE.get(c, c), idata))
    if idata == odata and not args.force:
        continue
    root, ext = os.path.splitext(ifile)
    ofile = f'{root}.f2h{ext}'
    if not args.quiet:
        print(f'{ifile} -> {ofile}')
    with open(ofile, 'w') as fp:
        fp.write(odata)
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