반응형

내가 komoran을 쓰는 이유는 새로운 단어를 등록하기 편하다는거다. 다른것들은 모두 새로운 단어를 등록하면 다시 컴파일해야 되고 보통 귀찮은게 아니다.

 

그러다 찾은게 komoran인데 komoran은 문제가 머냐하면 이상한 한글이나 특수문자나 이런거에 상당히 예민하다. 예를 들면 '즤엉이'라는 단어가 들어오면 에러가 난다. 즉 한글이 아닌 이상한 단어라고 해야하나. 특수문자도 아닌것이 한글도 아닌것이 komoran이 머지 이 글자는? 이란 생각이 들면 에러가 나는것 같다.

 

그래서 이상한 단어가 나오면 그 단어는 패스하고 넘어가도록 하는 코드를 만들어보았다.

 

import re, unicodedata
from PyKomoran import *
 
def normalize_and_strip(text: str) -> str:
    if text is None:
        return ""
    t = unicodedata.normalize("NFKC", str(text))
    # 제어/포맷/결합기호 제거
    t = "".join(ch for ch in t if unicodedata.category(ch) not in ("Mn", "Me", "Cf"))
    # C0/C1 제어문자 공백화
    t = re.sub(r'[\x00-\x1F\x7F\u0080-\u009F]', ' ', t)
    # 한글/영문/숫자/공백만 남기기
    t = re.sub(r"[^\uAC00-\uD7A3a-zA-Z0-9\s]", " ", t)
    # 공백 정리
    return " ".join(t.split())

def chunk_by_length(s: str, max_len: int = 160):
    out, cur, cur_len = [], [], 0
    for tok in s.split():
        add = len(tok) + (1 if cur else 0)
        if cur_len + add > max_len:
            if cur: out.append(" ".join(cur))
            cur, cur_len = [tok], len(tok)
        else:
            cur.append(tok); cur_len += add
    if cur: out.append(" ".join(cur))
    return out

def komoran_nouns_safe(text: str):
    # 1) 정규화/정리
    text = normalize_and_strip(text)
    if not text:
        return []

    nouns = []
    for piece in chunk_by_length(text, max_len=160):
        toks = piece.split()

        # 2) **토큰별 사전 테스트**: 에러 유발 토큰 사전 필터링
        safe_toks = []
        for tok in toks:
            try:
                # 토큰 단독 테스트 (여기서 에러나면 그 토큰만 제외)
                _ = komoran.get_nouns(tok)
                safe_toks.append(tok)
            except Exception:
                # 문제 토큰 기록 후 스킵 (예: '즤엉이')
                print("스킵 토큰:", repr(tok))
                continue

        if not safe_toks:
            continue

        # 3) 안전 토큰만 합쳐서 분석
        sent = " ".join(safe_toks)
        try:
            nouns.extend(komoran.get_nouns(sent))
        except Exception:
            # 혹시 여기서도 실패하면 토큰 단위로 개별 분석
            for tok in safe_toks:
                try:
                    nouns.extend(komoran.get_nouns(tok))
                except Exception:
                    print("최종 스킵:", repr(tok))
                    continue
    return nouns
 
sentence="즤엉이 대한민국"
pos=komoran_nouns_safe(sentence)
 

 

이렇게 하면 "즤엉이"는 건너뛰게 된다. 물론 이렇게하면 시간이 엄청 걸린다. 그래도 에러나서 멈춰 있는거보단 낫다. 그리고 이런 단어만 따로 모아두면 다음에 이런 단어가 들어오면 빼주면 되는데 그런 작업은 각자 해보자.

반응형

+ Recent posts