아래는 말뭉치 전처리 코드입니다.
# 문장
text = 'You say goodbye and I say hello.'
text = text.lower()
text = text.replace('.',' .')
# 단어 목록
words = text.split(' ')
# 단어ID와 단어의 대응표
word_to_id = {}
id_to_word = {}
for word in words:
if word not in word_to_id:
new_id = len(word_to_id)
word_to_id[word] = new_id
id_to_word[new_id] = word
print(id_to_word)
print(word_to_id)
>>> print(id_to_word)
{0: 'you', 1: 'say', 2: 'goodbye', 3: 'and', 4: 'i', 5: 'hello', 6: '.'}
>>> print(word_to_id)
{'you': 0, 'say': 1, 'goodbye': 2, 'and': 3, 'i': 4, 'hello': 5, '.': 6}
위 코드를 이용해서 말뭉치를 이용하기 위한 함수를 만듭니다.
common폴더의 util.py파일에 해당 함수를 저장해줍니다.
def preprocess(text):
text = text.lower()
text = text.replace('.', ' .')
words = text.split(' ')
word_to_id = {}
id_to_word = {}
for word in words:
if word not in word_to_id:
new_id = len(word_to_id)
word_to_id[word] = new_id
id_to_word[new_id] = word
corpus = np.array([word_to_id[w] for w in words])
return corpus, word_to_id, id_to_word