[Python beginner] Extract prefectures and cities from addresses (3 lines).

Conclusion

Prefectures


import re
#Prefectures only
address = "1 Nishi-Shinjuku, Shinjuku-ku, Tokyo-1-1"
matches = re.match('Tokyo|Hokkaido|(?:Kyoto|Osaka)Fu|.{2,3}Prefecture' , address)
print(matches.group()) 
#--->Tokyo

Ward


import re
#Ward only
address = "1 Nishi-Shinjuku, Shinjuku-ku, Tokyo-1-1"
ku_number = address.find('Ward')
print(address[:ku_number+1])  #If not, blanks are returned
#--->Shinjuku-ku, Tokyo

city


import re
#City only
address = "1 Yokoyama-cho, Hachioji-shi, Tokyo-1"
shi_number = address.find('city')
print(address[:shi_number+1])  #If not, blanks are returned#If not, blanks are returned
#--->Hachioji, Tokyo

Towns and villages can also be obtained with .find ().

Recommended Posts

[Python beginner] Extract prefectures and cities from addresses (3 lines).
[Python] Extract only numbers from lists and character strings
Python, yield, return, and sometimes yield from
Read and use Python files from Python
[Python beginner] Divide one list (5 lines).
About Python, from and import, as
Extract text from images in Python
[python] Extract text from pdf and read characters aloud with Open-Jtalk
[Beginner] Extract character strings with Python
Extract database tables with CSV [ODBC connection from R and python]
Extract strings from files in Python
Tips: [Python] Randomly restore and extract an array from a fasta file
Extract lines that match the conditions from a text file with python
Extract every n elements from an array (list) in Python and Ruby
Extract images from cifar and CUCUMBER-9 datasets
From Python to using MeCab (and CaboCha)
Line graphs and scale lines in python
# 5 [python3] Extract characters from a character string
[Python beginner] Join two lists alternately (5 lines).
Porting and modifying doublet-solver from python2 to python3.
[Beginner] Installing Python and running programs (Windows)
[Python] (Line) Extract values from graph images
Extract text from PowerPoint with Python! (Compatible with tables)
Python scraping Extract racing environment from horse racing site
Firebase: Use Cloud Firestore and Cloud Storage from Python
Study from Python Reading and writing Hour9 files
[Python] How to read data from CIFAR-10 and CIFAR-100
[Python] Find coordinates from two angles and distance
Load and execute command from yml in python
PHP and Python integration from scratch on Laravel
Generate and output plantuml object diagram from Python object
Extract data from a web page with Python
Extract images and tables from pdf with python to reduce the burden of reporting