LoginSignup
13
12

More than 1 year has passed since last update.

【Python3】括弧と括弧内文字列削除

Last updated at Posted at 2019-06-18

不動産のデータを普段から触っていると,物件名称ひとつとってもフォーマットがまちまちです.

その代表的なものとして,「括弧と括弧内文字列が邪魔ない状態で管理したい」というものがありますが,汎用的な関数な気がするので乗せておきます.

ちなみに,括弧内にさらに括弧があってもちゃんと削除できます.

output

import re

def delete_brackets(s):
    """
    括弧と括弧内文字列を削除
    """
    """ brackets to zenkaku """
    table = {
        "(": "(",
        ")": ")",
        "<": "<",
        ">": ">",
        "{": "{",
        "}": "}",
        "[": "[",
        "]": "]"
    }
    for key in table.keys():
        s = s.replace(key, table[key])
    """ delete zenkaku_brackets """
    l = ['([^(|^)]*)', '【[^【|^】]*】', '<[^<|^>]*>', '[[^[|^]]*]',
         '「[^「|^」]*」', '{[^{|^}]*}', '〔[^〔|^〕]*〕', '〈[^〈|^〉]*〉']
    for l_ in l:
        s = re.sub(l_, "", s)
    """ recursive processing """
    return delete_brackets(s) if sum([1 if re.search(l_, s) else 0 for l_ in l]) > 0 else s

usage

s = "渋谷ソラスタ (旧呼称:(仮称)南平台プロジェクト)"
delete_brackets(s) # '渋谷ソラスタ\u3000'

logic

brackets_2_zenkaku

はじめに想定しうる半角の括弧を全部全角にする

delete zenkaku_brackets

括弧内に括弧が入ってない文字列を削除

'([^(|^)]*)' というのが,
'('と')'に囲まれた文字列でかつ,'('と')'を含まない文字列にマッチする正規表現

です.

recursive processing

上のdelete zenkaku_bracketsを一度行うだけでは全部の括弧に対応できないので,再帰処理をしています.再帰処理については再帰関数を理解するための最もシンプルな例を参考にさせていただきました.

return delete_brackets(s) if sum([1 if re.search(l_, s) else 0 for l_ in l]) > 0 else s

は,

文字列sにまだ括弧が残っていれば再度実行し,もし残っていなければそのときのsを返す

というロジックです.

13
12
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
13
12