ssut / py-hanspell

파이썬 한글 맞춤법 검사 라이브러리. (네이버 맞춤법 검사기 사용)
MIT License
331 stars 117 forks source link

KeyError: Result 에러 해결 방법을 좀 더 간편하게 수정해 보았습니다. #48

Open issuebombom opened 7 months ago

issuebombom commented 7 months ago

초기에는 issue #47 해결방법을 적용하신 뒤 이후 매일 변경되는 passportKey에 대해서 아래와 같이 코드를 사용하면 번거롭게 매번 passportKey를 수동으로 변경하지 않으셔도 될 것 같아 공유드립니다.

현 시점에서는 잘 작동하지만 html에서 passportKey가 더이상 노출되지 않게 된다면 작동하지 않을 것입니다.

import re
import requests

def get_passport_key():
    """네이버에서 '네이버 맞춤법 검사기' 페이지에서 passportKey를 획득

        - 네이버에서 '네이버 맞춤법 검사기'를 띄운 후 
        html에서 passportKey를 검색하면 값을 찾을 수 있다.

        - 찾은 값을 spell_checker.py 48 line에 적용한다.
    """

    url = "https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=0&ie=utf8&query=네이버+맞춤법+검사기"
    res = requests.get(url)

    html_text = res.text

    match = re.search(r'passportKey=([^&"}]+)', html_text)
    if match:
        passport_key = match.group(1)
        return passport_key
    else:
        return False

def fix_spell_checker_py_code(file_path, passportKey):
    """획득한 passportkey를 spell_checker.py파일에 적용
    """

    pattern = r"'passportKey': '.*'"

    with open(file_path, 'r', encoding='utf-8') as input_file:
        content = input_file.read()
        modified_content = re.sub(pattern, f"'passportKey': '{passportKey}'", content)

    with open(file_path, 'w', encoding='utf-8') as output_file:
        output_file.write(modified_content)

    return 

# before run
spell_checker_file_path = './hanspell/spell_checker.py'

passport_key = get_passport_key()
if passport_key:
    fix_spell_checker_py_code(spell_checker_file_path, passport_key)
else:
    print("passportKey를 찾을 수 없습니다.")
Park-Young-Bin commented 3 months ago

해당 오류를 해결하려고 하는데, 작성해주신 코드는 어떤 파일에 입력을 해야하는지 궁금합니다!