반응형

NLTK 에러시 - Resource punkt not found 일때 

아래 다운로드 추가하면 됩니다. 

 

import nltk
nltk.download()

import os
from konlpy.tag import Okt

import nltk
nltk.download()

from nltk import word_tokenize, pos_tag, ne_chunk 
sentence = 'Mike is working at IT Centre' 

# 토큰화, 품사태깅 pos_tag 후 -> ne_chunk 개체명인식 
sentence = pos_tag(word_tokenize(sentence)) 
print(sentence) 

# 개체명 인식 
sentence = ne_chunk(sentence) 
print(sentence)

반응형
반응형

NLTK 설치

저는 아나콘다 환경에서 파이썬을 사용하고 있으므로 이미 루트 가상환경에 NLTK가 설치가 되어있었습니다. KoNLPy와 다르게 별도의 설정등을 해줄 필요가 없습니다.아나콘다 내에서 가상환경을 따로 만들어 설치를 해줄시엔 해당 가상환경 activate 후에

> conda install nltk]
> conda update nltk

위 명령어를 입력하여 설치해주면 됩니다.

 

하지만 예제를 수행하면 여러 에러 메세지들을 볼 수 있습니다. 예를들어 nltk.download('words'), nltk.download('maxent_ne_chunker')를 하라는 등의 메세지가 뜨면 오류메세지에 뜬 명령어 그대로 입력해서 별도의 모듈들을 설치해주면 됩니다.

 

 

○ 예제 시행해보기

from nltk import word_tokenize, pos_tag, ne_chunk

sentence = 'Mike is working at IT Centre'

# 토큰화, 품사태깅 pos_tag 후 -> ne_chunk 개체명인식
sentence = pos_tag(word_tokenize(sentence))
print(sentence)

# 개체명 인식
sentence = ne_chunk(sentence)
print(sentence)

 

결과

# [('Mike', 'NNP'), ('is', 'VBZ'), ('working', 'VBG'), 
# ('at', 'IN'), ('IT', 'NNP'), ('Centre', 'NNP')]
# (S
#   (GPE Mike/NNP)
#   is/VBZ
#   working/VBG
#   at/IN
#   (ORGANIZATION IT/NNP Centre/NNP))

 

 

 

 

 

○ 몇 가지 기능 살펴보기

 

1. nltk.Text()

 

nltk.Text()는 자연어 데이터의 탐색을 편리하게 해주는 다양한 기능들을 제공합니다.

import nltk
from nltk.corpus import gutenberg
from nltk import regexp_tokenize

f = gutenberg.fileids()
doc_en = gutenberg.open('austen-emma.txt').read()

pattern = r'''(?x) ([A-Z]\.)+ | \w+(-\w+)* | \$?\d+(\.\d+)?%? | \.\.\. | [][.,;"'?():-_`]'''
tokens_en = regexp_tokenize(doc_en, pattern)

en = nltk.Text(toekns_en)

 

테스트를 하기 위해 NLTK에서 제공하는 제인오스틴의 소설 Emma데이터를 다운받습니다. 이후 문서를 토큰으로 나누는 작업을 해주었는데 한국어를 토크나이즈하거나 품사태깅, 개체명 태깅 등을 할 때는 KoNLPy를 이용하는 것이 훨씬 낫다고 봅니다.


예를 들어 NLTK에서 '나는 바보다'라는 문장에서 '바보다'라는 토큰의 개체명을 'Organization'으로 인식하는 등의 문제가 있습니다. 그래서 한국어 처리를 할 때에는 nltk를 데이터를 탐색하는 용도로 많이 사용하는 듯 합니다.

 

 

2. 그래프 그리기

 

en.plot(50) 

en문서의 50개의 토큰만 플롯으로 그려보았습니다.

 


en.dispersion_plot(['Emma','Frank','Jane'])

 


 

 

 

 

 

 

 

3. 문서 탐색

 

print(len(en.tokens)) # 토큰의 개수 확인
print(len(set(en.tokens))) # Unique 토큰의 개수 확인
en.vocab() # Frequency Distribution 확인
print(en.count('Emma')) # 'Emma'의 개수
en.concordance('Emma', lines=5) # 'Emma'가 들어있는 5개의 문장만 출력
en.similar('Emma')
en.similar('Frank') # 비슷한 단어 찾기
> 결과

> 191061
> 7927
> FreqDist({',': 12018, '.': 8853, 'to': 5127, 'the': 4844, 'and': 4653, 'of': 4278, '"': 4187, 'I': 3177, 'a': 3000, 'was': 2385, ...})
> 865
> Displaying 5 of 865 matches:
                                     Emma by Jane Austen 1816 ] VOLUME I CHAPT
                                     Emma Woodhouse , handsome , clever , and
both daughters , but particularly of Emma . Between them it was more the int
 friend very mutually attached , and Emma doing just what she liked ; highly e
r own . The real evils , indeed , of Emma situation were the power of havi
> she it he i harriet you her jane him that me and all they them there herself was hartfield be
mr mrs emma harriet you it her she he him hartfield them jane that isabella all herself look i me

 

그래프를 그리는 것 외에도 토큰의 개수나 frequency distribution등을 확인하여 데이터의 구조를 살펴보는데 좋은 기능들도 많이 제공하고 있습니다.

 

 


4. Chunking nltk.RegexParser()

 

Chunking 얕은 구문 분석, 음성 및 단구 (명사구와 같은)를 식별하는 것

tokens = "The little yellow dog barked at the Persian cat".split()
tags_en = nltk.pos_tag(tokens)

parser_en = nltk.RegexpParser("NP: {<DT>?<JJ>?<NN.*>*}")
chunks_en = parser_en.parse(tags_en)
chunks_en.draw()
결과

[('The', 'DT'),
 ('little', 'JJ'),
 ('yellow', 'NN'),
 ('dog', 'NN'),
 ('barked', 'VBD'),
 ('at', 'IN'),
 ('the', 'DT'),
 ('Persian', 'NNP'),
 ('cat', 'NN')]

 

 


5. 워드클라우드 그리기

 

import nltk
ko = nltk.Text(tokens_ko, name='대한민국 국회 의안 제 1809890호')

 한국어 예제를 하나 불러옵니다.

 

# 예제의 빈도분포(frequency distribution) 살펴보기

print(ko.vocab())
type(ko.vocab()) # 데이터타입, 속성목록 확인
dir(ko.vocab()) # 예제문서의 단어사전 살펴보기

data = ko.vocab().items()
print(data)
print(type(data)) # items()를 이용하면 빈도분포의 item 전체를 set형태로 확인 가능합니다.
> 결과

> FreqDist({'.': 61, '의': 46, '육아휴직': 38, '을': 34, '(': 27, ',': 26, '이': 26, ')': 26, '에': 24, '자': 24, ...})
> nltk.probability.FreqDist
> ['B',
 'N',
 ...
 'items',
 ...
 'pop',
 'popitem',
 'pprint',
 'r_Nr',
 'setdefault',
 'subtract',
 'tabulate',
 'unicode_repr',
 'update',
 'values']
 
 > dict_items([('명', 5), ('예상된', 3), ('하나', 1), ('11', 2), ('팀', 2), ...])
<class 'dict_items'>

데이터 탐색@@

 

import csv
with open('words.csv', 'w', encoding='utf-8') as f:
    f.write('word,freq\n')
    writer = csv.writer(f)
    writer.writerows(data)

탐색한 데이터 set을 words.csv라는 파일에 저장하여 워드클라우드를 그리는데 이용하도록 하겠습니다.

 

<!DOCTYPE html>
<html>
<head>
  <style>
    text:hover {
        stroke: black;
    }
  </style>
  <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
  <script src="d3.layout.cloud.js"></script>
</head>
<body>
  <div id="cloud"></div>
  <script type="text/javascript">
    var weight = 3,   // change me
        width = 960,
        height = 500;

    var fill = d3.scale.category20();
    d3.csv("words.csv", function(d) {
        return {
          text: d.word,
          size: +d.freq*weight
        }
      },
      function(data) {
        d3.layout.cloud().size([width, height]).words(data)
          //.rotate(function() { return ~~(Math.random() * 2) * 90; })
          .rotate(0)
          .font("Impact")
          .fontSize(function(d) { return d.size; })
          .on("end", draw)
          .start();

        function draw(words) {
          d3.select("#cloud").append("svg")
              .attr("width", width)
              .attr("height", height)
            .append("g")
              .attr("transform", "translate(" + width/2 + "," + height/2 + ")")
            .selectAll("text")
              .data(words)
            .enter().append("text")
              .style("font-size", function(d) { return d.size + "px"; })
              .style("font-family", "Impact")
              .style("fill", function(d, i) { return fill(i); })
              .attr("text-anchor", "middle")
              .attr("transform", function(d) {
                return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
              })
            .text(function(d) { return d.text; });
        }
      });
  </script>
</body>
</html>

위 코드를 index.html로 저장하고 words.csv가 있는 폴더내에 저장합니다.

 

python -m http.server 8888 

그리고 프롬프트웨 위 명령어를 입력하여 실행시켜준 뒤, http://localhost:8888로 접속하면,

 

생성된 워드클라우드를 확인할 수 있습니다.



출처: https://ebbnflow.tistory.com/147 [Dev Log : 삶은 확률의 구름]

반응형
반응형

1. Anaconda 3버전과 Visual Studio Code (이하 vscode) 준비

(일반 Python을 사용하시는 분은 pip을 같이 설치해주세요)

 

2. vscode에 Python (Microsoft) Extension 설치

 

3. 가상환경에 autopep8 패키지 설치 (PEP8 기준 자동정렬 기능 추가)

(아나콘다 기준)  conda install --name 가상환경명 autopep8

(pip 기준)  pip install autopep8

 

위의 명령어로 직접 설치하지 않아도 vscode 내에서 자동정렬 키를 누르면 패키지를 설치하겠냐는 팝업이 뜹니다.

 

4. 가상환경에 pylint 패키지 설치 (구문오류 체크)

(아나콘다 기준)  conda install --name 가상환경명 pylint

(pip 기준)  pip install pylint

 

위의 명령어로 직접 설치하지 않아도 저장이나 build 시 패키지를 설치하겠냐는 팝업이 뜹니다.

 

 

5. 마우스 우클릭 혹은 Command Palette(F1키)에서 Run Python File in Terminal을 선택하면 Terminal에서 실행

 

입맛에 따라 단축키를 지정해주시면 빠르게 실행결과를 볼 수 있습니다.


[오류]conda: 'conda' 용어가 cmdlet,함수,스크립트 파일 또는 실행할 수 있는 프로그램 이름으로 인식되지 않습니다.

 

VSCODE 에서 python 연동하기. 

 

Visual Studio Code의 기본 터미널이 Windows의 Power Shell로 설정되어 있기 때문.

 

    "terminal.integrated.defaultProfile.windows":"Command Prompt",
    "python.terminal.activateEnvInCurrentTerminal": true

settings.json에서 cmd.exe 추가하고, python.terminal.activateEnvInCurrentTerminal : true 로 변경하면  

해당 편집파일에서 "Run Python File" 실행시 cmd 실행되면서 python ENV 가 activate가 되면서 파일이 실행 된다. 

 

 

 

 

 

https://velog.io/@dbal9357/conda-conda-%EC%9A%A9%EC%96%B4%EA%B0%80-cmdlet%ED%95%A8%EC%88%98%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%ED%8C%8C%EC%9D%BC-%EB%98%90%EB%8A%94-%EC%8B%A4%ED%96%89%ED%95%A0-%EC%88%98-%EC%9E%88%EB%8A%94-%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%A8-%EC%9D%B4%EB%A6%84%EC%9C%BC%EB%A1%9C-%EC%9D%B8%EC%8B%9D%EB%90%98%EC%A7%80-%EC%95%8A%EC%8A%B5%EB%8B%88%EB%8B%A4

 

[오류]conda: 'conda' 용어가 cmdlet,함수,스크립트 파일 또는 실행할 수 있는 프로그램 이름으로 인식

원인 Visual Studio Code의 기본 터미널이 Windows의 Power Shell로 설정되어 있기 때문.해결이 기본 터미널의 종류를 cmd 또는 Git Bash로 변경하면 오류없이 실행이 가능.방법setting.json파일이 열리면 ""안에 c

velog.io

 

반응형
반응형

[tensorflow] 한글 음절 인식기 - hangul-syllable-recognition

 

https://github.com/junstar92/hangul-syllable-recognition

 

GitHub - junstar92/hangul-syllable-recognition: hangul syllable recognition 한글 음절 인식기

hangul syllable recognition 한글 음절 인식기. Contribute to junstar92/hangul-syllable-recognition development by creating an account on GitHub.

github.com

 

Introduction

한글은 조합이 다양하기 때문에 영어에 비해서 OCR 성능이 조금 떨어진다고 알고 있다.

다양한 폰트와 손글씨 데이터를 가지고, 얼마나 한글을 잘 인식하는지 확인하기 위해서 프로젝트를 진행했다.

Getting started

python and pakage version

python3 == 3.8.3

tensorflow_gpu == 2.3.0

numpy == 1.19.5

argparse == 1.1

pandas == 1.2.0

cv2 == 4.5.1

streamlit == 0.74.1

streamlit_drawable_canvas

반응형
반응형

점프 투 플라스크

https://wikidocs.net/book/4542

 

점프 투 플라스크

**점프 투 플라스크 오프라인 책 출간 !! (2020.11)** * [책 구입 안내](https://wikidocs.net/102760)

wikidocs.net

 

반응형
반응형


Websites to learn Python

반응형
반응형

파이콘 한국 2021 - https://2021.pycon.kr/  

 

온라인 컨퍼런스 10/2(토)~10/3(일)

 

페이스북 : https://www.facebook.com/pyconkorea/

 

#python  #pycon  #파이썬

반응형
반응형

파이썬 라이브러리

https://wikidocs.net/book/5445

 

위키독스

온라인 책을 제작 공유하는 플랫폼 서비스

wikidocs.net

https://pybo.kr/pybo/question/list/qna/

 

질문과답변 - 파이보

 

pybo.kr

 

반응형

+ Recent posts