반응형

벡터화

  • 자연어가 기계가 이해할 수 있도록 숫자로 변환해주는 과정

 

원-핫 인코딩(One-Hot Encoding)

  • 단어 집합의 크기를 벡터의 차원으로 하고, 표현하고 싶은 단어의 인덱스에 1의 값을 부여하고, 다른 인덱스에는 0을 부여하는 벡터 표현 방식
  • 원-핫 인코딩 과정
    1. 각 단어에 고유한 인덱스 부여
    2. 표현하고 싶은 단어의 인덱스에 1, 아닌 단어에는 0 부여

 

원-핫 인코딩 실습1

from my_tokenizer import tokenize

# 사전 생성
def make_vocab(tokens):
    word2index = {}
    for voca in tokens:
        if voca not in word2index.keys():
            word2index[voca] = len(word2index)
    return word2index

# 원핫인코딩
def one_hot_encoding(word, word2index):
    one_hot_vector = [0] * (len(word2index))
    index = word2index[word]
    one_hot_vector[index] = 1
    return one_hot_vector


if __name__ == '__main__':
    document = '안녕하세요. 이번에 같이 교육받게 된 김지선이라고 합니다.'
    tokens = tokenize(document, 'lemma')
    word2index = make_vocab(tokens)
    # print(word2index)
    print('dictionary:', word2index) 
    print(one_hot_encoding('같이', word2index))

 

 

원-핫 인코딩 실습2

import nltk
from nltk.tokenize import sent_tokenize
from nltk import WordPunctTokenizer
from nltk.stem import LancasterStemmer
from nltk.stem import WordNetLemmatizer


class Tokenizer:
    def __init__(self, tokenize_type): # 클래스로 만들어서 self 가 자동으로 붙음
        self.type = tokenize_type

    def make_vocab(self, document):
        tokens = self.tokenize(document)
        word2index = {'<unk>': 0}
        for voca in tokens:
            if voca not in word2index.keys():
                word2index[voca] = len(word2index)
        self.vocab = word2index
        print('dictionary:', self.vocab)

    # types = ['stem', 'lemma', 'pos']
    def tokenize(self, document):
        words = []
        sentences = sent_tokenize(document)  # sentence tokenizing
        for sentence in sentences:
            words.extend(WordPunctTokenizer().tokenize(sentence))  # word tokenizing
        if self.type == 'stem':
            lancaster_stemmer = LancasterStemmer()
            tokenized = [lancaster_stemmer.stem(w) for w in words]  # stemming
        elif self.type == 'lemma':
            lemmatizer = WordNetLemmatizer()
            tokenized = [lemmatizer.lemmatize(w).lower() for w in words]  # lemmatizing
        elif self.type == 'pos':
            # tokenized = nltk.pos_tag(words) # pos tagging
            tokenized = [token[0] + '/' + token[1] for token in nltk.pos_tag(words)]
        else:
            raise TypeError
        return tokenized

    def one_hot_encoding(self, word):
        one_hot_vector = [0] * (len(self.vocab))
        if word not in self.vocab:
            word = "<unk>"
        index = self.vocab[word]
        one_hot_vector[index] = 1
        return one_hot_vector

    def get_vector(self, sentence):
        # return 2차원 배열
        tokens = self.tokenize(sentence)
        print('Tokenized:', tokens)
        return [self.one_hot_encoding(token) for token in tokens]


if __name__ == '__main__':
    document = 'Hi! 안녕하세요.\n 이번에 같이 교육받게 된 김지선\n이라고 합니다.'
    tokenizer = Tokenizer('lemma')
    tokenizer.make_vocab(document)
    print(tokenizer.get_vector('hi, 같이 김지선'))

 

 

반응형
반응형

전처리 이해

  • 토큰화
    • 주어진 데이터를 토큰(Token)이라 불리는 단위로 나누는 작업
    • 토큰이 되는 기준은 다를 수 있음(어절, 단어, 형태소, 음절, 자소 등)
  • 정제
    • 불필요한 데이터(Noise data)를 제거하는 작업
  • 정규화
    • 표현 방법이 다른 단어들을 통합시켜서 같은 단어로 만들어주는 작업
  • 문장 토큰화
  • 문장분리
  • 단어 토큰화“Hello, World!” -> “Hello”, “,”, “World”, “!”
  • 구두점 분리, 단어 분리

 

토큰화 실습

# 문장 분리 
from nltk.tokenize import sent_tokenize 
text = "Hello, world. These are NLP tutorials." 
print(sent_tokenize(text))

 

 

import nltk from nltk import WordPunctTokenizer 
nltk.download('punkt') 
text = "Hello, world. These are NLP tutorials." 
print(WordPunctTokenizer().tokenize(text))

 

 


정제&정규화

  • 불필요한 데이터를 제거하는 작업
  • 표기가 다른 단어들의 통합 예시) US, USA -> USA, 어간 추출(stemming), 표제어 추출(lemmatization)
  • 대소문자 통합: 문장 첫 글자 문제
  • 불필요한 단어 제거 예시) 불용어(stopwords), 영어가 아닌 외국어
  • 정규표현식

어간추출&표제어 추출

  • 어간추출(stemming)
    • 축약형으로 변환
  • 표제어추출(lemmatization)
    • 품사 정보가 보존된 형태의 기본형으로 변환

 

어간추출&표제어추출 실습

### 어간 추출 ###

from nltk import WordPunctTokenizer
from nltk.stem import PorterStemmer
from nltk.stem import LancasterStemmer

text = "Hello, world. These are NLP tutorials."
words = WordPunctTokenizer().tokenize(text)
print(words)
porter_stemmer = PorterStemmer()
print([porter_stemmer.stem(w) for w in words])
lancaster_stemmer = LancasterStemmer()
print([lancaster_stemmer.stem(w) for w in words])

 

#### 표제어 추출 ####

import nltk
from nltk import WordPunctTokenizer
from nltk.stem import WordNetLemmatizer
nltk.download('wordnet')
text = "Hello, world. These are NLP tutorials."
words = WordPunctTokenizer().tokenize(text)
lemmatizer = WordNetLemmatizer()
print(words)
print([lemmatizer.lemmatize(w) for w in words])

 

반응형

 

불용어 실습

## 불용어 확인 ##

import nltk
from nltk.corpus import stopwords

nltk.download('stopwords')
english_stopwords = stopwords.words('english')
print(len(english_stopwords))
print(english_stopwords[:10])

 

## 불용어 제거 ##
from nltk.corpus import stopwords
from nltk import WordPunctTokenizer

text = "Hello, world. These are NLP tutorials."
stop_words = stopwords.words('english')
stop_words.append('hello')

words = WordPunctTokenizer().tokenize(text)
words = [word.lower() for word in words]


result = []
for word in words:
    if word not in stop_words:
        result.append(word)
print(words)
print(result)

 

POS Tagging, Named Entity Recognition 실습

# POS tagging (part of speeck tagging)
# Named Entity Recognition

import nltk
from nltk import WordPunctTokenizer

nltk.download('averaged_perceptron_tagger')
nltk.download('words')
nltk.download('maxent_ne_chunker')

text = "Hello, world. These are NLP tutorials."

word = WordPunctTokenizer().tokenize(text)
tagged = nltk.pos_tag(word)
entities = nltk.chunk.ne_chunk(tagged)

print(word)
print(tagged)
print(entities)

 

토크나이저 실습

import nltk
from nltk.tokenize import sent_tokenize
from nltk import WordPunctTokenizer
from nltk.stem import LancasterStemmer
from nltk.stem import WordNetLemmatizer

types = ['stem', 'lemma', 'pos']

def tokenize(document, type):
    words = []

    sentences = sent_tokenize(document) # sentence tokenizing
    for sentence in sentences:
        words.extend(WordPunctTokenizer().tokenize(sentence)) # word tokenizeing

    # sentence tokenizing
    # word tokenizing
    # 타입에 따라서 토큰으로 분리
    if type == 'stem':
        lancaster_stemmer = LancasterStemmer()
        tokenized = ([lancaster_stemmer.stem(w) for w in words]) # stemming
    elif type == 'lemma':
        lemmatizer = WordNetLemmatizer()
        tokenized = ([lemmatizer.lemmatize(w) for w in words]) # lemmatizing
    elif type == 'pos':
        # tokenized = nltk.pos_tag(words) # pos tagging
        tokenized = [token[0]+'/'+token[1] for token in nltk.pos_tag(words)]
    else:
        raise TypeError
    return tokenized

if __name__ == '__main__':
    document = '안녕하세요. 이번에 같이 교육받게 된 김지선이라고 합니다.'
    print(tokenize(document, 'pos'))

 

반응형
반응형

파이썬 문자열 함수

실습

text = "hello"
upper_text = text.upper()
print(upper_text)

sentence = 'hello python'

caplitalzed_sentence = sentence.capitalize()
print(caplitalzed_sentence)

title_sentence = sentence.title()
print(title_sentence)

swapped_title_sentence = title_sentence
print(swapped_title_sentence)

text = ' hello python '
print(text)

print(text.strip())
print(text.rstrip())
print(text.lstrip())

print(text.replace(' ', '.'))
print(text.replace('hello', 'bye'))

text = 'hello python'
print(text)

print(text.split())

print(text.split('p'))

test = '1,62,7,543,12\n'
split_test = test.strip().split(',')
print(split_test)
print(list(map(int, test.strip().split(','))))

join_split_test = ','.join(split_test)
print(join_split_test)

test1 = 'hello python\n this is nlp tutorial\n string function ex\n'
print(test1)
print(test1.splitlines())

text = '123'
print(text.isdigit())

text = 'abc'
print(text.isalpha())

text = '1a2b3c'
print(text.isdigit())
print(text.isalpha())
print(text.isalnum())

text = 'hello'
print(text.islower())
print(text.isupper())

text = 'HELLO'
print(text.islower())
print(text.isupper())

text = 'hello'
print(text.startswith('h'))
print(text.endswith('o'))

text = 'hi1 hi2 hi3 hi4'
print(text.count('hi'))
print(text.find('hi'))
print(text.find('hi', 1))
print(text.rfind('hi'))
print(text.find('hi5'))
print(text.index('hi'))
#print(text.index('hi5'))

print(text.index('hi5'))

→ hi5 라는 string을 찾을 수 없어서 오류가 남

정규표현식

  • 복잡한 문자열을 처리할 때 사용하는 기법
  • 파이썬만의 고유 문법이 아니라 문자열을 처리하는 모든 곳에서 활용
  • re라는 모듈 사용

\b : 단어의 경계(word boundary) 문자자체라서 \하나를 더 써야한다.

정규표현식 실습

import re

# . 한 개의 임의의 문자
r = re.compile("a.c")
print(r.search("abd"))
print(r.search("abc"))

# ? 앞의 문자가 존재 or 미존재
r = re.compile("abc?")
print(r.search("abc"))
print(r.search("ab"))

# * 앞의 문자가 0개 이상
r = re.compile("ab*c")
print(r.search("ac"))
print(r.search("abc"))
print(r.search("abbbc"))

# + 앞의 문자가 1개 이상
r = re.compile("ab+c")
print(r.search("ac"))
print(r.search("abc"))
print(r.search("abbbc"))

# ^ 시작되는 글자를 지정
r = re.compile("^bc")
print(r.search("abc"))
print(r.search("bc"))

# {숫자} 해당 문자를 숫자만큼 반복
r = re.compile("ab{2}c")
print(r.search("abc"))
print(r.search("abbc"))
print(r.search("abbbc"))

# {숫자1, 숫자2} 해당 문자를 숫자1 이상, 숫자2 이하만큼 반복
r = re.compile("ab{2,4}c")
print(r.search("abc"))
print(r.search("abbc"))
print(r.search("abbbc"))
print(r.search("abbbbc"))
print(r.search("abbbbbc"))

# {숫자,} 해당 문자를 숫자 이상 만큼 반복
r = re.compile("ab{2,}c")
print(r.search("abc"))
print(r.search("abbc"))
print(r.search("abbbc"))
print(r.search("abbbbc"))
print(r.search("abbbbbc"))

# [문자] 문자들 중 한개의 문자와 매치
# [a-zA-Z]는 알파벳 전부를 의미, [0-9]는 숫자 전부를 의미
r = re.compile("[abc]")
print(r.search("a"))
print(r.search("d"))

# [^문자] 제외한 모든 문자를 매치
r = re.compile("[^ac]")
print(r.search("a"))
print(r.search("d"))

정규표현식 실습2

##### 숫자로만 이루어진 단어를 찾아서 반환 #####
sentence = '1 star lstar 4 dollar 4doller 10 people 10people'

# coding
# 1, 4, 10 결과로 반환하도록
r = re.compile("\\b[0-9]+\\b")
result = r.findall(sentence)
print(result)


## 92년생 찾기 ###
def get_years_92(birthdays):
    r = re.compile('92[0-9]{4}')
    result = []
    # coding
    for birth in birthdays:
        if r.match(birth):
            result.append(birth)
    return result

def get_years_92_function(birthdays):
    result = []
    # coding
    for birth in birthdays:
        if birth.startswith('92'):
            result.append(birth)
    return result

birthdays = ['911211', '920109', '930205', '941124', '900502', '920412', '931121', '940608', '950926']

print(get_years_92(birthdays))
print(get_years_92_function(birthdays))

### 뉴스 기사에서 이메일 주소 찾기 ###
news = '기사제목\n기사본문\nhello@chosun.com\n2020-09-08\n'

r = re.compile('[a-zA-Z0-9]+@[a-zA-Z0-9]+\.com')
result = r.search(news)
print(result)
print(result.group())


* String 만 나오게 하는 방법 *

  1. result.start() 또는 result.end() 함수를 활용해서 시작위치랑 끝 위치를 받아와서 news[result.start():result:end()] 출력
  2. result.group() 함수 호출
반응형
반응형

파이썬 설치

https://www.python.org/downloads/windows/

Python Releases for Windows

The official home of the Python Programming Language

www.python.org


설치하고 실행할 때 Add Python 3.6 to PATH 클릭!!!
Install Now 클릭

 

파이참 설치

https://www.jetbrains.com/pycharm/download/#section=windows

Download PyCharm: Python IDE for Professional Developers by JetBrains

Download the latest version of PyCharm for Windows, macOS or Linux.

www.jetbrains.com

Community 로 다운로드


실행!


반응형

'프로그래밍 언어 > Python' 카테고리의 다른 글

[Python] 라이브러리 다운로드 에러  (0) 2020.09.27
[Python] 기초 문법  (0) 2020.09.27

+ Recent posts