[NLP] 챗봇 단어 사전 구축 및 시퀀스 생성 : Build word dict and Create sequences

KingU·2022년 6월 6일
0

NLP

목록 보기
14/14
post-thumbnail

단어 사전 구축 및 시퀀스 생성


의도 분류 및 개체명 인식 모델의 학습을 위하여 단어 사전 구축


# 필요한 모듈 임포트
from tensorflow.keras import preprocessing
import pickle

# 말뭉치 데이터 읽어오기
def read_corpus_data(filename):
    with open(filename, 'r') as f:
        data = [line.split('\t') for line in f.read().splitlines()]
        data = data[1:] # 헤더 제거
    return data
    
# 말뭉치 데이터 변수 설정
corpus_data = read_corpus_data('./corpus.txt')

# 말뭉치 데이터에서 키워드만 추출해서 사전 리스트 생성
p = Preprocess()
dict = []
for c in corpus_data:
    pos = p.pos(c[1])
    for k in pos:
        dict.append(k[0])
        
# 사전에 사용될 word2index 생성
# 사전의 첫 번째 인덱스에는 OOV 사용
# dict 리스트를 단어 인덱스 딕서녀리 word_index 데이터로 만들기
tokenizer = preprocessing.text.Tokenizer(oov_token='OOV')
tokenizer.fit_on_texts(dict)
word_index = tokenizer.word_index

# 사전 파일 생성
# 생성된 단어 인덱스 딕셔너리 word_index 객체를 파일로 저장
f = open("chatbot_dict.bon", "wb")
try:
    pickle.dump(word_index, f)
except Exception as e:
    print(e)
finally:
    f.close()





전처리 클래스에 단어 인덱스 시퀀스 변환 메서드 추가


# 전처리 클래스
class Preprocess:
    def __init__(self, word2index_dic='', userdic=None):
        # 단어 인덱스 사전 불러오기
        if(word2index != ''):
            f = open(word2index_dic, "rb")
            self.word_index = pickle.load(f)
            f.close
        
    # 형태소 분석기 POS 태거
    def pos(self, sentence):
        return self.komoran.pos(sentence)
        
    # 불용어 제거 후 필요한 품사 정보만 가져오기
    def get_keywords(self, pos, without_tag=False):
        f = lambda x: x in self.exclusion_tags
        word_list = []
        for p in pos:
            if f(p[1]) is False:
                word_list.append(p if without_tag is False else p[0])
        return word_list
    
    # 키워드를 단어 인덱스 시퀀스로 변환
    def get_wordidx_sequence(self, keywords):
        if self.word_index is None:
            return []
        w2i = []
        for word in keywords:
            try:
                w2i.append(self.word_index[word])
            except KeyError:
                # 해당 단어가 사전에 없는 경우 OOV 처리
                w2i.append(self.word_index['OOV'])
        return w2i





당신의 시간이 헛되지 않는 글이 되겠습니다.
I'll write something that won't waste your time.

profile
원하는 것을 창조하고 창조한 것을 의미있게 사용하자

0개의 댓글