0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

住所から都道府県を抽出する

Posted at

はじめに

Pythonで正規表現を使用して住所から都道府県を抽出します

環境

~ % python -V
Python 3.11.9

pandasを使用しています

~ % pip list | grep pandas
pandas             2.2.3

正規表現

(東京都|北海道|(?:京都|大阪)府|.{2,3}県)

準備

住所の一覧を用意します
※ChatGPTで適当に作成しています

address.csv
東京都新宿区西新宿2-8-1
北海道札幌市中央区北1条西2丁目
大阪府大阪市北区梅田3丁目1-1
京都府京都市中京区寺町通御池下ル下本能寺前町522
神奈川県横浜市西区みなとみらい2-3-5
愛知県名古屋市中区栄3丁目16-1
福岡県福岡市博多区博多駅中央街1-1
兵庫県神戸市中央区加納町6丁目5-1
宮城県仙台市青葉区中央1丁目1-1
広島県広島市中区基町6-27

コード

main.py
import pandas as pd
import re
pd.set_option('display.unicode.east_asian_width', True)

def extract(address):
    m = re.match('(東京都|北海道|(?:京都|大阪)府|.{2,3}県)', address)
    return m.group()

df = pd.read_csv('address.csv', header=None, names=['address'])
df['pref']=df['address'].apply(extract)
print(df)

結果

711f75d7af2da1019e45.png

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?