Pythonで住所から都道府県名だけを削除する

スポンサーリンク

Pythonで日本の住所から都道府県名だけを削除してみます。

■Python

Google Colaboratory(Google Colab),Python3.7.10

■replace()関数を使用し住所から都道府県名だけを削除する

では、早速replace()関数を使用し住所から都道府県名だけを削除するスクリプトを書いていきます。

■コード

text = "大阪府大阪市中央区大阪城1番1号"
text = text.replace('北海道','')
text = text.replace('青森県','')
text = text.replace('岩手県','')
text = text.replace('宮城県','')
text = text.replace('秋田県','')
text = text.replace('山形県','')
text = text.replace('福島県','')
text = text.replace('茨城県','')
text = text.replace('栃木県','')
text = text.replace('群馬県','')
text = text.replace('埼玉県','')
text = text.replace('千葉県','')
text = text.replace('東京都','')
text = text.replace('神奈川県','')
text = text.replace('新潟県','')
text = text.replace('富山県','')
text = text.replace('石川県','')
text = text.replace('福井県','')
text = text.replace('山梨県','')
text = text.replace('長野県','')
text = text.replace('岐阜県','')
text = text.replace('静岡県','')
text = text.replace('愛知県','')
text = text.replace('三重県','')
text = text.replace('滋賀県','')
text = text.replace('京都府','')
text = text.replace('大阪府','')
text = text.replace('兵庫県','')
text = text.replace('奈良県','')
text = text.replace('和歌山県','')
text = text.replace('鳥取県','')
text = text.replace('島根県','')
text = text.replace('岡山県','')
text = text.replace('広島県','')
text = text.replace('山口県','')
text = text.replace('徳島県','')
text = text.replace('香川県','')
text = text.replace('愛媛県','')
text = text.replace('高知県','')
text = text.replace('福岡県','')
text = text.replace('佐賀県','')
text = text.replace('長崎県','')
text = text.replace('熊本県','')
text = text.replace('大分県','')
text = text.replace('宮崎県','')
text = text.replace('鹿児島県','')
text = text.replace('沖縄県','')

print(text)

replace()関数の括弧内には、第1の引数,パラメータとして都道府県名を渡します。第2の引数,パラメータとして置き換え後の文字を渡します。今回は削除しますので、「””」とします。

これで、住所内に都道府県名が含まれていれば、都道府県名を置き換えて、test変数に格納されます。

最後に、test変数に格納された情報をprint()関数で出力させてみます。

■実行・検証

スクリプトを作成後、このスクリプトを実行してみます。

実行してみると、replace()関数を使用したことで、住所に含まれている都道府県名が置き換えされて削除され、都道府県名が削除された住所をprint()関数で出力させることができました。

コメント

タイトルとURLをコピーしました