# 토크나이저 구현

## 개요

학습할 데이터에 대한 전처리(토큰화 및 정제) 과정을 수행하는 토크나이저 구현에 대하여 기술한다.

## 수행 과정 명세

### 문자열 전처리

입력받은 문자열에 대하여 형태소 분석을 하기 전에 전처리 과정을 수행한다. 구체적인 전처리 과정은 다음과 같다.

* Emoji 패턴 제거

```coffeescript
emoji_pattern = re.compile("["
        u"\U0001F600-\U0001F64F"  # emoticons
        u"\U0001F300-\U0001F5FF"  # symbols & pictographs
        u"\U0001F680-\U0001F6FF"  # transport & map symbols
        u"\U0001F1E0-\U0001F1FF"  # flags (iOS)
                           "]+", flags=re.UNICODE)
```

* 모든 공백 문자 제거

```coffeescript
re.sub('\s'," ", doc)
```

* 모든 영어 소문자로 변환

```coffeescript
 doc.lower()
```

* 모든 특수 기호 제거

```coffeescript
 re.sub('[-=+,#/\?:^$.@*\"※~&%ㆍ!』\\‘|\(\)\[\]\<\>`\'…》]', ' ', doc)
```

* 한글 및 영어를 제외한 모든 문자 제거

```coffeescript
re.compile('[^ ㄱ-ㅣ가-힣|a-z]+').sub('', doc)
```

### 형태소 분석

전처리가 완료된 문서를 기반으로 각 문장에 대하여 형태소 분석 과정을 수행한다. 형태소 분석에는 Python의 Konlpy 모듈을 임포트하여 수행한다.

```coffeescript
def konlpy_morp_analy(text):
	#print("docs_length:",len(text))
	try:
		result = komoran.pos(text)
		return result
	except:
		return []

def konlpy_parser(m_list):
	tokens = []
	df = pd.DataFrame(columns = ["text", "type"])
	for data,m_type in m_list:
		if is_valid(data, m_type):
			tokens += [data]
	return tokens
```

### 유효성 검증

형태소 분석 결과에 대하여 2차 전처리 과정을 수행한다.

* 단어의 길이가 1자리 이하이거나, 불용어 사전 내에 존재할 경우 제외

```coffeescript
h_s_set = h_stopwords
if len(data) <= 1 or data in h_s_set:
		return False
```

* 해당 단어가 영어이고, 영어 불용어 사전에 포함되어 있거나 단어의 길이가 2 이하일 경우 제외

```coffeescript
e_s_set = set(stopwords.words('english'))
if m_type == "SL" and (data in e_s_set or len(data) <= 2):
		return False
```

* 비속어를 포함하여 토픽에 기여를 하지 못할만한 각종 단어 제외

```coffeescript
if data in stop_set:
		return False
```

* 한글이지만 단일 자모음을 포함할 경우 제외

```coffeescript
if any(i in single_stop for i in data):
		return False
```

* 영어 및 한자로 분류되지만 한글이 섞여 있을 경우 제외

```coffeescript
if m_type not in ["SH", "SL"] and 
data != re.compile('[^ ㄱ-ㅣ가-힣|a-z]+').sub('', data):
		return False
```

* 단어의 총 길이가 15자 이상일 경우 제외(의미없는 문자의  나열인 경우가 큼)

```coffeescript
if len(data) >= 15:
		return False
```

* 해당 형태소가 일반 명사, 고유 명사, 영어, 한자 중 하나일 경우, 유효한 토큰으로 취급

```coffeescript
sign_list = sign_dict.values()
	if m_type in sign_list:
		return True
```

## 코드 실행 예제

![](/files/-LooAULrh7DmxARum8lF)

SOOJLE의 토크나이저는 해당 문서 내에서 토픽이 관련이  있을 만한 토큰만을 추출해내야 하기 때문에 주로 명사 쪽의 단어들을 많이  추출되는 것을 확인할 수 있다. &#x20;

단 해당 토크나이저가 아직 완벽한 것은 아니다. 2번째 예제처럼 "이랑" 이라는 토큰이 추출된 것은 앞 단어가 영어이기 때문에 해당 영어 명사를 보충하는 단어인지, 아니면 영어와 한글의 합성어인지 머신이 명확하게 판단할 수 없었기 때문이다.&#x20;

## 소스 코드 배포

{% embed url="<https://github.com/iml1111/IML_Tokenizer>" %}

### **실행 요구사항**

| 분류   | 설명          |
| ---- | ----------- |
| 플랫폼  | Github      |
| 라이센스 | MIT License |

| 분류    | 버전명          |
| ----- | ------------ |
| 개발 언어 | Python 3.7.1 |

| 라이브러리 요구사항             |
| ---------------------- |
| konlpy==0.5.1          |
| nltk==3.4.4            |
| numpy==1.16.4          |
| pandas==0.24.2         |
| python-dateutil==2.8.0 |
| pytz==2019.1           |
| six==1.12.0            |
| JPype1==0.7.0          |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://soojle.gitbook.io/project/undefined-2/undefined-4/undefined.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
