1단계. 데이터 미리 살펴보기
데이터를 살펴보세요: 크기와 구조 같은 주요 특징을 살펴보면서 문장, 단락, 텍스트가 어떻게 이루어졌는지 알아보세요.
- 이 데이터가 얼마나 유용할지를 가늠합니다.
- 어떤 부분이 도움이 될지 텍스트를 살펴봅니다.
‘변신’의 경우에는:
- 특별히 눈에 띄는 오타나 실수는 없습니다.
- 반점, 아포스트로피, 따옴표, 물음표 등의 문장 부호가 있습니다.
- 전반적으로 단순합니다.
2단계. 공백, 문장 부호, 대소문자 정규화하기
두 가지 방법이 있습니다
- 직접 텍스트를 정제하기
- NLTK 라이브러리 사용하기
보통 후자를 선호하기는 하지만, 텍스트 정제를 학습하기 위해 직접 하는 방법을 살펴봅시다.
<직접 해보기>
몇 줄의 파이썬 코드로 직접 텍스트를 정제할 수 있습니다.
‘읽어들이기’, ‘분할하기’, ‘소문자로 바꾸기’의 세 가지 주요 단계가 있습니다.
1. 데이터 읽어들이기
filename = 'metamorphosis_clean.txt'
file = open(filename, 'rt')
text = file.read()
file.close()
‘metamorphosis_clean.txt’ 파일이 없다면, 위의 개요 부분을 읽어주세요.
전형적인 파이썬 파일 읽어들이기 과정과 동일합니다.
2. 토큰화
토큰화는 단락을 문장으로 분할하거나 문장을 개별적인 단어로 분할하는 것을 말합니다.
문장은 비슷한 과정을 통해 개별적인 단어와 문장 부호로 분할될 수 있습니다. 가장 흔한 방법은 공백을 기준으로 단어를 나누는 것입니다.
단어가 축약어, 생략어, 또는 소유격일 때 문제가 생길 수 있습니다. 예를 들어 문장 부호를 사용하는 이름 같은 경우에 말입니다. (O’Neil처럼요).
공백으로 나누기
filename = 'metamorphosis_clean.txt'
file = open(filename, 'rt')
text = file.read()
file.close()
words = text.split()
print(words[:100])
['One', 'morning,', 'when', 'Gregor', 'Samsa', 'woke', 'from', 'troubled', 'dreams,', 'he', 'found', 'himself', 'transformed', 'in', 'his', 'bed', 'into', 'a', 'horrible', 'vermin.', 'He', 'lay', 'on', 'his', 'armour-like', 'back,', 'and', 'if', 'he', 'lifted', 'his', 'head', 'a', 'little', 'he', 'could', 'see', 'his', 'brown', 'belly,', 'slightly', 'domed', 'and', 'divided', 'by', 'arches', 'into', 'stiff', 'sections.', 'The', 'bedding', 'was', 'hardly', 'able', 'to', 'cover', 'it', 'and', 'seemed', 'ready', 'to', 'slide', 'off', 'any', 'moment.', 'His', 'many', 'legs,', 'pitifully', 'thin', 'compared', 'with', 'the', 'size', 'of', 'the', 'rest', 'of', 'him,', 'waved', 'about', 'helplessly', 'as', 'he', 'looked.', '"What\'s', 'happened', 'to', 'me?"', 'he', 'thought.', 'It', "wasn't", 'a', 'dream.', 'His', 'room,', 'a', 'proper', 'human']
잘 되는 것처럼 보입니다만, 결과를 자세히 보면 몇 가지 문제를 발견할 수 있습니다.
"wasn't", "dream.", "room,"
문장 부호를 삭제해야 합니다. 즉, “텍스트 정제”를 해야 합니다.
단어로 분할하기
filename = 'metamorphosis_clean.txt'
file = open(filename, 'rt')
text = file.read()
file.close()
import re
words = re.split(r'\W+', text)
print(words[:100])
['One', 'morning', 'when', 'Gregor', 'Samsa', 'woke', 'from', 'troubled', 'dreams', 'he', 'found', 'himself', 'transformed', 'in', 'his', 'bed', 'into', 'a', 'horrible', 'vermin', 'He', 'lay', 'on', 'his', 'armour', 'like', 'back', 'and', 'if', 'he', 'lifted', 'his', 'head', 'a', 'little', 'he', 'could', 'see', 'his', 'brown', 'belly', 'slightly', 'domed', 'and', 'divided', 'by', 'arches', 'into', 'stiff', 'sections', 'The', 'bedding', 'was', 'hardly', 'able', 'to', 'cover', 'it', 'and', 'seemed', 'ready', 'to', 'slide', 'off', 'any', 'moment', 'His', 'many', 'legs', 'pitifully', 'thin', 'compared', 'with', 'the', 'size', 'of', 'the', 'rest', 'of', 'him', 'waved', 'about', 'helplessly', 'as', 'he', 'looked', 'What', 's', 'happened', 'to', 'me', 'he', 'thought', 'It', 'wasn', 't', 'a', 'dream', 'His', 'room']
정규 표현식을 좋아하시나요? 아니라고요? 그래야만 합니다. 텍스트 데이터를 처리하는 데 아주 유용합니다.
이 코드에서 \W+ 는 하나 이상의 단어 문자를 찾습니다. ( [a-zA-Z0-9_]+와 같습니다). 아주 간단하죠!
이제 "wasn't"로부터 "wasn"와 "t"를 얻었습니다.
공백으로 분할하고 문장 부호 제거하기
filename = 'metamorphosis_clean.txt'
file = open(filename, 'rt')
text = file.read()
file.close()
words = text.split()
import string
table = str.maketrans('', '', string.punctuation)
stripped = [w.translate(table) for w in words]
print(stripped[:100])
['One', 'morning', 'when', 'Gregor', 'Samsa', 'woke', 'from', 'troubled', 'dreams', 'he', 'found', 'himself', 'transformed', 'in', 'his', 'bed', 'into', 'a', 'horrible', 'vermin', 'He', 'lay', 'on', 'his', 'armourlike', 'back', 'and', 'if', 'he', 'lifted', 'his', 'head', 'a', 'little', 'he', 'could', 'see', 'his', 'brown', 'belly', 'slightly', 'domed', 'and', 'divided', 'by', 'arches', 'into', 'stiff', 'sections', 'The', 'bedding', 'was', 'hardly', 'able', 'to', 'cover', 'it', 'and', 'seemed', 'ready', 'to', 'slide', 'off', 'any', 'moment', 'His', 'many', 'legs', 'pitifully', 'thin', 'compared', 'with', 'the', 'size', 'of', 'the', 'rest', 'of', 'him', 'waved', 'about', 'helplessly', 'as', 'he', 'looked', 'Whats', 'happened', 'to', 'me', 'he', 'thought', 'It', 'wasnt', 'a', 'dream', 'His', 'room', 'a', 'proper', 'human']
이번에는 python3의 문자열 함수를 사용했습니다. 정규 표현식이나 다른 방법을 선호한다면 그 방법을 사용해도 됩니다.
최종적으로, "wasn't"에서 "wasnt" 를 얻었습니다.
3. 대문자화
텍스트는 보통 문장의 시작과 적절한 명사 강조를 반영하기 위한 대문자를 많이 사용합니다. 가장 흔한 접근법은 간단하게 모두 소문자로 바꾸는 것이지만, “US”를 “us”로 바꿀 때처럼 어떤 경우에는 소문자로 바꾸는 것이 의미를 바꿀 수도 있다는 점을 명심해야 합니다.
filename = 'metamorphosis_clean.txt'
file = open(filename, 'rt')
text = file.read()
file.close()
words = text.split()
words = [word.lower() for word in words]
print(words[:100])
['one', 'morning,', 'when', 'gregor', 'samsa', 'woke', 'from', 'troubled', 'dreams,', 'he', 'found', 'himself', 'transformed', 'in', 'his', 'bed', 'into', 'a', 'horrible', 'vermin.', 'he', 'lay', 'on', 'his', 'armour-like', 'back,', 'and', 'if', 'he', 'lifted', 'his', 'head', 'a', 'little', 'he', 'could', 'see', 'his', 'brown', 'belly,', 'slightly', 'domed', 'and', 'divided', 'by', 'arches', 'into', 'stiff', 'sections.', 'the', 'bedding', 'was', 'hardly', 'able', 'to', 'cover', 'it', 'and', 'seemed', 'ready', 'to', 'slide', 'off', 'any', 'moment.', 'his', 'many', 'legs,', 'pitifully', 'thin', 'compared', 'with', 'the', 'size', 'of', 'the', 'rest', 'of', 'him,', 'waved', 'about', 'helplessly', 'as', 'he', 'looked.', '"what\'s', 'happened', 'to', 'me?"', 'he', 'thought.', 'it', "wasn't", 'a', 'dream.', 'his', 'room,', 'a', 'proper', 'human']
토큰화보다 텍스트를 소문자로 바꾸는 것이 훨씬 간단합니다. lower()를 사용해 코드 한 줄로 처리할 수 있습니다.
텍스트를 직접 정제하는 방법을 배웠습니다. 여전히 부족함을 느낀다면 NLTK를 시도할 준비가 된 것입니다. nltk-다운로더를 설치하고 실행합시다.
< NLTK >
Natural Language Toolkit은 축약어로 NLTK이며 텍스트 작업과 모델링을 위한 파이썬 라이브러리입니다.
고수준 api를 제공하여 다양한 정제 메소드를 유연하게 구현할 수 있도록 합니다.
1. NLTK 설치하기
pip install -U nltk
python -m nltk.downloader all
* 아래의 링크를 참조하여 각 OS에 맞는 NLTK 설치를 해보세요.
comment
20201005
카프카의 ‘변신’ (머릿말-꼬릿말 잘라낸 파일)
카프카의 ‘변신’ - 전문(UTF-8) 링크(페이지에서 우클릭-저장)
http://www.gutenberg.org/cache/epub/5200/pg5200.txt