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?

More than 1 year has passed since last update.

[python] カタカナを全角と半角をパッケージ使わずに交換する

Last updated at Posted at 2022-10-25
# 半角カナと全角カナを交換
def conversion_kana(kana):
    zen = "アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲンァィゥェォッャュョ"
    han = "アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲンァィゥェォッャュョ"
    zen_da = "ガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポヴ"
    han_da = "ガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポヴ"
    kana_dic = {
        zen: han,
        han: zen,
        zen_da: han_da,
        han_da: zen_da
    }
    res = ""
    # 入力文字を一文字づつ走査する
    for i, k in enumerate(kana):
        if k[0] in ['', '']:
            continue

        # 文字が半角の濁点なら次の一文字を追加する
        han_d_flg = False
        if not len(kana) == i+1:
            if kana[i+1] in ['', '']:
                k += kana[i+1]
                han_d_flg = True

        # 文字が所属するキーを探す
        zen_d_flg = False
        ok_flg = False
        for key in kana_dic.keys():
            if key[0] == "":
                zen_d_flg = True

            # キーを一文字づつ走査する
            if k in key:
                # 半角濁点はインデックスを半分にする、全角濁点はインデックスを倍にする、それ以外はそのまま
                if han_d_flg:
                    int_key = int(key.find(k)/2)
                    if not len(kana_dic[key]) == int_key:
                        res += kana_dic[key][int_key]
                elif zen_d_flg:
                    res += kana_dic[key][key.find(k)*2] + kana_dic[key][key.find(k)*2+1]
                else:
                    res += kana_dic[key][key.find(k)]

                ok_flg = True
                break

        # 文字が見つからない場合はそのまま代入する
        if not ok_flg:
            res += k

    return res

0
0
2

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?