주소 및 우편 번호를 검색할 수 있는 대화식 콘솔 응용 프로그램

13867 단어 PythonPython3

입문


AdventCalendar의 첫 번째 투고입니다.
python 상자가 비어 있기 때문에, 제가 외람되게 한 가지 투고하는 것을 허락해 주십시오.
지난번 기사는 여기서 → LINE Notify + Python에서 날씨 정보를 얻는 방법

배경


너무 이르기 때문에, 올해도 12월이다.
12월이면 크리스마스고 연하장을 준비하는 시기다.
연하장을 보내고 싶을 때 주소는 알지만 우편번호가 뭐였지?그런 생각이 드세요?(반대로)
이제 주소만 검색하면 우편 번호가 나타납니다.
인터넷 환경이 없어도 주소, 우편번호를 검색할 수 있는 도구가 있었으면 좋겠어요.
python에 익숙해지면서 간단한 컨트롤러 프로그램을 만들어 보았습니다.
우편 번호에서 주소를 검색하는 사례가 매우 많다
나는 주소에서 우편번호를 검색하는 사례가 많지 않다고 생각해서 어떤 상황에서도 대응할 수 있도록 해 보았다.

환경


・Mac OS Mojave
・python3
・pyinstaller

처리 사양


흐름도는 다음과 같다.
기본적으로 우편 번호를 입력한 주소를 저장할 수 있다
입력한 주소(일부 지명만 해당)에 대한 우편 번호를 저장할지 여부를 대화식으로 선택하십시오.

소스 코드


우체국 홈페이지에서 우편번호 데이터 다운로드 페이지에서 "KEN_ALL.CSV"를 다운로드하여/Users/바로 아래에 놓고 읽습니다.
FindAddress_for_Mac.py
import sys

# Set Path including "KEN_ALL.CSV" for Mac OS X
csv_path = "/Users/KEN_ALL.CSV"

def GetAddress():
    postal_code = input("Type target postal code:")
    fp = open(csv_path, "r", encoding="shift_jis")
    for line in fp:
        line = line.replace(' ', '') # cut space
        line = line.replace('"', '') # cut double quatation
        cells = line.split(",")      # split by comma
        code = cells[2]  # Postal code
        pref = cells[6]  # Prefucture
        city = cells[7]  # City name
        ad = cells[8]    # Address name
        title = pref + city + ad
        if code.find(postal_code) != -1:
            print(title)
    fp.close()

def GetPostalCode():
    addr = input("Type target address:")
    fp = open(csv_path, "r", encoding="shift_jis")
    for line in fp:
        line = line.replace(' ', '') # cut space
        line = line.replace('"', '') # cut double quatation
        cells = line.split(",")      # split by comma
        code = cells[2]  # Postal Code
        pref = cells[6]  # Prefucture
        city = cells[7]  # City name
        ad = cells[8]    # Address name
        title = pref + city + ad
        if title.find(addr) != -1:
            print(code + ":" + title)
    fp.close()


def main():
    print("\n")
    print("####################################################")
    print("################### FINDADDRESS ####################")
    print("####################################################")
    print("\n")
    print("[DISCRIPTION]")
    print(" This tool is to get address or postal code.")
    print(" If you type '1', you can get unknown address by typing postal code.")
    print(" If you type '2', you can get unknown postal code by typing KEYWORD about address name.")
    print("\n")

    while True:
        print("[OPERATION]")
        print("input the following number which you want to get.")
        number = input("[1:Address  2:PostalCode  99 (or SPACE):Close]:")
        if number.isdigit() != 1: # Filter non-integer value
            sys.exit()
        int_number = int(number)  # Convert String to Integer
        if int_number == 1:       # The case that user types "1"
            GetAddress()
            print("\n")
        elif int_number == 2:     # The case that user types "2"
            GetPostalCode()
            print("\n")
        elif int_number == 99:    # The case that user types "99"
            sys.exit()
        else:                     # Exception handling
            print("Invalid Number. Type again.")
            print("\n")

if __name__ == "__main__":
    main()

pyinstaller로 exe화


exe화된 순서는 이쪽 보도가 참조하기 쉽기 때문이다.
PyInstaller exe로 파일화
https://qiita.com/takanorimutoh/items/53bf44d6d5b37190e7d1

실행 결과


예를 들어 도쿄 도강동구 신목장의 주소와 우편번호를 검색해 보자.
1 주소 검색에 우편번호 "136082"를 입력하면 신목장 주소
동경 도강동구 신목장이 옮겨 저장되다.
2의 우편번호 검색에 주소의 키워드인'신목장'을 입력하면 신목장 문자가 포함된 주소는 모든 우편번호와 주소가 저장됩니다.

주의사항


사용하기 전에 터미널 기본 설정에서 셸이 끝날 때의 설정 설정을'창 닫기'로 설정하십시오.이것을 하지 않으면 프로그램이 끝난 후에 컨트롤러가 남습니다.

마지막


앞으로도 시간이 된다면 Windows, Linux 대응 버전을 설치해 보세요.

좋은 웹페이지 즐겨찾기