본문 바로가기

python

16. 텍스트마이닝

728x90
반응형

파이썬의 리스트가 스택 구조임을 확인하시오

 

데이터의 추가와 삭제가 한쪽 방향에서 일어 나는 (후입선출)

STACK

: 책쌓고 책하나씩 빼기

 

 

같은방향으로 입력,출력이 일어나는 (선입선출)

: 한줄씩 서서 입장     <<---A<B<C<<---

: 오라클에서 데이터의 무결성을 보호하기 위한 lock 바로 구조.

 

             scott(A)              scott(B)                    scott(C)

1. update emp

    set sal = 9000

   where ename='ALLEN';

                                                2. update emp

                                                     set sal =0

                                                      where ename='ALLEN'; 

                                                                                                3. update emp

                                                                                                    set sal

                                                                                                    where ename='ALLEN';

4. commit;

 

1 수행하면 2,3 lock 걸림.

4 commit 수행하면 2번만 풀리고, 3 그대로 lock.

순서대로 작업처리하고, 순서가 아직인 것은 대기한다.

=> 구조 (선입선출)

 

 

 

문제246.

파이썬의 리스트가 스택구조임을 확인하시오

                              

                          후입선출

a=[]

a.append(1)

a.append2)

a.append(3)

print(a)

 

문제247.

다시 숫자를 빼내시오(나중에 들어온 숫자가 먼저 나가게끔 하시오)

후입선출!

 

a.pop()

print(a)

 

.pop()   :   나중에 들어온게 빠져나간다 !!!!!!!!!

 

 

■데이터 정제를 파이썬으로 하는 방법

"텍스트 마이닝 클래스를 생성"

 

79. 개의 문자열 합치기(+)

예제:

filename=input('저장할 파일 이름을 입력하세요:')

a='당신이 저장한 파일은 '+filename+' 입니다'

print(a)

 

 

문제248.

아래와 같이 영화 대본에서 특정 단어가 있는지

찾는 스크립트를 구현하기 위해 두개의 질문을 물어보게 하시오

 

a=input('분석할 스크립트명을 입력하세요~')   winter.txt

b=input('찾을 단어를 입력하세요~')      elsa

 

print(find_word())

 

결과: d:\\winter.txt

            elsa

 

def find_word():

    a=input('분석할 스크립트명을 입력하세요 ~ ')

    b=input('찾을 단어를 입력하세요 ~ ')

    print("d:\\"+a)

    return(b)

 

print(find_word())

 

 

80. 문자열을 반복해서 새로운 문자열로 만들기

예제:

msg1='여러분'

print(msg1*3)

 


 

 

81. 문자열에서 특정 문자 있는지 확인하기(in)

예제:

msg=input('임의 문장을 입력하세요~ ')

if 'a' in msg:

    print('당신이 입력한 문자에는 a 가 있습니다')

else:

    print('당신이 입력한 문자에는 a 가 없습니다')

 

 

 

문제249.

아래와 같이 겨울왕국 대본에서 elsa 검색해서 건이 나오는지 출력하는

함수를 생성하시오(문제97번에서 다뤘음)

 

from time import sleep

script = input('분석할 대본을 입력하세요.')

file = open('d://%s' %script,'r')

word = input('찾고자 하는 단어를 입력하세요.')

cnt = 0

 

for winter_list in file:

    a = winter_list.split(' ')

    for i in a:

        cnt += i.lower().count(word)

        msg = '\r %d' %cnt

        print(msg, end='')

        sleep(0.001)

 


 

 

문제250. 위의 함수를 클래스로 구성하여 아래와 같이 실행될 있게 하시오

(클래스 이름: Text_mining() )

 

tm=Text_mining()

print(tm.find_word() )

 

#*****return end='' 먹음

----------------------------------------------------------

class Text_mining:

    def __init__(self):

        self. script = input('분석할 대본을 입력하세요.')

        self.file = open('d://%s' %self.script,'r')

        self.word = input('찾고자 하는 단어를 입력하세요.')

   

    def find_word(self):

        cnt = 0

        for winter_list in self.file:

            a = winter_list.split(' ')

            for i in a:

                cnt += i.lower().count(self.word)

                msg = '\r %d개' %cnt

                #print(msg, end='')

        return (msg)

                #sleep(0.001)      

   

tm=Text_mining()

print(tm.find_word())

 

 

 

82. 문자열에서 특정 문자열 있는지 확인하기(in)

예제:

msg=input('임의의 문장을 입력하세요:')

if 'is' in msg:

    print('당신이 입력한 문장에는 is 가 있습니다')

else:

    print('당신이 입력한 문장에는 is 가 없습니다')

 

 

문제251.

겨울왕국 대본에서 단어들만 출력하시오

 

def find_word():

    file=open('d:\\winter.txt','r')

    #sum=0

    for winter_list in file:

        a=winter_list.split(' ')

        for b in a:

            print(b)

find_word()

 

 

 

 

file=open('d:\\winter.txt','r')

    for winter_list in file:

        print(winter_list)   #txt 파일을 list

이렇게 돌려서 확인하고

 

file=open('d:\\winter.txt','r')

   

    for winter_list in file:

        print(winter_list)

        a=winter_list.split(' ')

        print(a)          #리스트를 공백으로 나눈게 a인데 출력되는 형태는?

이렇게도 확인해보기

 

 

 

 

문제252.

위의 출력된 결과중에서 엔터를 정제하시오 ( \n <-제거해라)

 

import re   #데이터 정제시 중요한 정규식 모듈

 

 

def find_word():

    file=open('d:\\winter.txt','r')

   

    for winter_list in file:

        #print(winter_list)

        a=winter_list.split(' ')

        #print(a)

        for b in a:

            #print(b)

            print(re.sub("\n",'',b).lower() )  #엔터 \n ' ' 변경해라

find_word()

 

 

 

문제253.

겨울왕국 대본에서 "-" 안나오게 출력하시오.

 

 

 

import re   #데이터 정제시 중요한 정규식 모듈

def find_word():

    file=open('d:\\winter.txt','r')

   

    for winter_list in file:

        #print(winter_list)

        a=winter_list.split(' ')

        #print(a)

        for b in a:

            #print(b)

            print(re.sub('[^A-z]','',b).lower() )

find_word()

                             

                       알파벳 대문자 A부터 소문자 z 제외한

                         나머지를 정제하여 출력하라.

 

 

******두개 한번에 쓰면

import re   #데이터 정제시 중요한 정규식 모듈

def find_word():

    file=open('d:\\winter.txt','r')

   

    for winter_list in file:

        #print(winter_list)

        a=winter_list.split(' ')

        #print(a)

        for b in a:

            #print(b)

            print(re.sub("\n",'',b).lower(),re.sub("-",'',b).lower() )

find_word()

 

좌측에 \n 정제한거,   우측에 - 제거한걸로 2개씩 출력됨

하나에 적용 시키려면??

import re

def find_word():

    file = open('d:\\winter.txt','r')

    sum = 0

    for winter_list in file:

        a = winter_list.split(' ')

        for b in a:

            c = re.sub('-', '', b)

            print( re.sub('\n', '', c).lower() )  #정제한 변수 c 에서 정제하라는

           

find_word()

 

 

 

문제254.

긍정단어집(positive-words.txt) 위의 스크립트를 이용해서

영단어만(다른거 정제시키고) 단어씩 출력되게 하시오

 

import re

def positive_word():

    file = open('d:\\positive-words.txt','r')

    #sum = 0

    for positive_list in file:

        a = positive_list.split(' ')

        for b in a:

            print(re.sub('[^A-z]','',b).lower() )

           

positive_word()

 


 

 

문제255.

위의 긍정단어들을 p_list 라는 비어있는 리스트에 전부 append 시키도록

코드를 변경하시오

 

import re

def positive_word():

    p_list=[]

    file = open('d:\\positive-words.txt','r')

    #sum = 0

    for positive_list in file:

        a = positive_list.split(' ')

        for b in a:

            c=re.sub('[^A-z]','',b).lower()

            p_list.append(c)

            #print(p_list)

    return p_list

           

p_list2=positive_word()

print(p_list2)

 

 

 

문제256.

위의 positive-word() 함수를 이용해서 find_word() 함수에서

겨울왕국 대본에 긍정단어가 있는지 출력되게 하시오

  | |

winter.txt winter-positive 있는지 출력하시오.

 

 

import  re

 

def positive_word():

    file = open("d:\\positive-words.txt",'r')

    p_list =[]

    for  winter_list  in  file:

        a = winter_list.split(' ')

        for  b  in  a:

            p_list.append( re.sub('[^A-z]','',b).lower() )

    return  p_list

   

 

def find_word():

    file = open("d:\\winter.txt",'r')

    sum = 0

    p_list2 = positive_word()

    for  winter_list  in  file:

        a = winter_list.split(' ')

        for  b  in  a:

            if re.sub('[^A-z]','',b).lower() in p_list2:

                sum = sum + 1

    print (sum)

  

find_word()

 

결과: 1062

 

근데

긍정단어는 +a 포함되어 있어서

re.sub '[^A-z]' 하면 +a 정제된다.

 

그러면

positive_word 에서

re.sub '\n' 처리해주고,

 

find_word 가서

 

 

import  re

 

def positive_word():

    file = open("d:\\positive-words.txt",'r')

    p_list =[]

    for  winter_list  in  file:

        a = winter_list.split(' ')

        for  b  in  a:

            p_list.append( re.sub('\n','',b).lower() )

    return  p_list

   

 

def find_word():

    file = open("d:\\winter.txt",'r')

    sum = 0

    p_list2 = positive_word()

    for  winter_list  in  file:

        a = winter_list.split(' ')

        for  b  in  a:

            if re.sub('[^A-z]','',b).lower() in p_list2:

                sum = sum + 1

    print (sum)

  

find_word()

 

 

 

문제257.

겨울왕국에 부정단어가 얼마나 있는지 알아내기 위한 함수를 생성하시오

 

positive_word():     #긍정단어를 리스트화 하는 함수

negative_word():    #부정단어를 리스트화 하는 함수

 

p_count():    #긍정단어의 갯수 세는 함수

n_count():   #부정단어의 갯수 세는 함수

 

 

import  re

 

def positive_word():

    file = open("d:\\positive-words.txt",'r')

    p_list =[]

    for  winter_list  in  file:

        a = winter_list.split(' ')

        for  b  in  a:

            p_list.append( re.sub('\n','',b).lower() )

    return  p_list

   

 

def nagative_word():

    file = open("d:\\negative-words.txt",'r')

    n_list =[]

    for  winter_list  in  file:

        a = winter_list.split(' ')

        for  b  in  a:

            n_list.append( re.sub('\n','',b).lower() )

    return  n_list

   

 

def p_count():

    file = open("d:\\winter.txt",'r')

    sum = 0

    p_list2 = positive_word()

    for  winter_list  in  file:

        a = winter_list.split(' ')

        for  b  in  a:

            if re.sub('[^A-z]','',b).lower() in p_list2:

                sum = sum + 1

    print (sum)

  

def n_count():

    file = open("d:\\winter.txt",'r')

    sum = 0

    n_list2 = nagative_word()

    for  winter_list  in  file:

        a = winter_list.split(' ')

        for  b  in  a:

            if re.sub('[^A-z]','',b).lower() in n_list2:

                sum = sum + 1

    print (sum)

   

n_count()   

 

 

 

 

문제258.(점심시간문제)

Text_mining() 클래스에 아래의 5가지 method 추가해서

생성하고

수행되는지 확인하시오!

 

positive_word():     #긍정단어를 리스트화 하는 함수

negative_word():    #부정단어를 리스트화 하는 함수

 

p_count():    #긍정단어의 갯수 세는 함수

n_count():   #부정단어의 갯수 세는 함수

find_word()   #스크립트의 특정 단어의 갯수를 세는 함수

 

tm=Text_mining()

tm.p_count()   #긍정단어 카운트

 

 

 

class Text_mining:

   

  

    def positive_word(self):

        import re

        file = open("d:\\positive-words.txt",'r')

        p_list =[]

        for  winter_list  in  file:

            a = winter_list.split(' ')

            for  b  in  a:

                p_list.append( re.sub('\n','',b).lower() )

        return  p_list

       

   

    def negative_word(self):

        import re

        file = open("d:\\negative-words.txt",'r')

        n_list =[]

        for  winter_list  in  file:

            a = winter_list.split(' ')

            for  b  in  a:

                n_list.append( re.sub('\n','',b).lower() )

        return  n_list

       

   

    def p_count(self):

        import re

        file = open("d:\\winter.txt",'r')

        sum = 0

        p_list2 = self.positive_word()

        for  winter_list  in  file:

            a = winter_list.split(' ')

            for  b  in  a:

                if re.sub('[^A-z]','',b).lower() in p_list2:

                    sum = sum + 1

        print (sum)

      

    def n_count(self):

        import re

        file = open("d:\\winter.txt",'r')

        sum = 0

        n_list2 = self.negative_word()

        for  winter_list  in  file:

            a = winter_list.split(' ')

            for  b  in  a:

                if re.sub('[^A-z]','',b).lower() in n_list2:

                    sum = sum + 1

        print (sum)

   

tm=Text_mining()

tm.p_count()   #긍정단어 카운트

                  #p_count() tm 에서 갖고와서 써야 하니까 self 써야함!

 

 

 

 

문제259.

'인공지능' 이라는 키워드로 중앙일보에서 기사검색을

mydata3.txt   m_list 라는 비어있는 변수에

단어별로 쪼개서

담으시오

 

def hangle_list():

    import re

    file = open("d:\\mydata3.txt",'r',encoding='UTF8') #유니코드 잡아주는거

    m_list =[]

    for  mydata3_list  in  file:

        a = mydata3_list.split(' ')

        for  b  in  a:

            c=re.sub('[^가-A-z]','',b) # 마지막!

            m_list.append(c)

    return m_list

print(hangle_list())

 

 

 

 

문제260.

인공지능 기사검색한 리스트를 워드 클라우드로 시각화 하시오

 

*wordcloud 모듈 설치 방법

아나콘다 프롬프트 창을 열고

>conda install -c conda-forge wordcloud

(일반 다른 설치랑 조금 다름)

 

 

준하가 보내준거 한글코드 -폴더열기- 이름바꾸기- 확장자 ttf .

 

 

 

from wordcloud import WordCloud, STOPWORDS      # 워드 클라우딩 모듈

import matplotlib.pyplot as plt                 # 시각화 모듈

from os import path                             # 텍스트 파일을 불러오기 위한 open, path 하기 위해 os 임포트

import re

 

d = path.dirname("d://")                        # 텍스트 파일이 있는 상위 디렉토리를 path로 지정

text = open(path.join(d, "mydata3.txt"), mode="r", encoding="UTF-8").read()     # 텍스트파일을 open 하는데 reading만 되게 (mode="r"), UTF-8 방식으로 불러옴(UTF-8)

 

text = re.sub("있다",'',text)  #너무 많이 나와서 정제해버리자!

text = re.sub("있는",'',text)

text = re.sub("하지만",'',text)

text = re.sub("것이다",'',text)

text = re.sub("대한",'',text)

text = re.sub("통해",'',text)

text = re.sub("함께",'',text)

text = re.sub("인공지능",'',text)

 

text = re.sub("hani",'',text)

text = re.sub("한다",'',text)

text = re.sub("하는",'',text)

text = re.sub("위해",'',text)

text = re.sub("co",'',text)

text = re.sub("kr",'',text)

text = re.sub("위한",'',text)

text = re.sub("했다",'',text)

text = re.sub("같은",'',text)

text = re.sub("것은",'',text)

 

 

wordcloud = WordCloud(font_path='C://Windows//Fonts//BMHANNA_11yrs_ttf',           # 폰트 위치(거의 기본적으로 C://Windows//Fonts 안에 들어있습니다)

                      stopwords=STOPWORDS, background_color='white',        # STOPWORDS 옵션은 공백/줄바꾸기 기준으로 단어를 추출해 냅니다

                      width=1000,                                           # background_color는 워드클라우드 배경색을 나타냅니다. 'black'으로하면 검은색이 됩니다.

                      height=800,                                           # width와 height는 워드클라우드의 크기를 지정해 줍니다.

                      colormap='jet').generate(text)                       # colormap은 워드 색깔을 지정해주는데 첨부한 색감표를 사용하시면 됩니다. generate() 메소드는

 

 

plt.figure(figsize=(13,13))                                                 # matplotlib의 pyplot을 figsize로 생성합니다

plt.imshow(wordcloud)                                                       # 워드 클라우드 이미지를 pyplot에 띄웁니다

plt.axis("off")                                                             # pyplot에 x, y축 표시를 없앱니다.

plt.show()

 

 


 


 

****글자색 바꾸고 싶으면

구글에서 python color map 찾아서 jet 자리에 적용시켜주면 .

 


 


 

 

 

*****"것으로" 라는 말도 지우고 싶다면?

text = re.sub("것으로",'',text)

 

 

 

 

문제261.

EBS 프로그램중에 레이디버그 게시판글들을 워드 클라우드로 시각화 하시오!

 

받은 파일 ladybug3.txt 아래코딩에 넣어주면 .

 

text = open(path.join(d, "mydata3.txt"), mode="r", encoding="UTF-8").read()

 


 


 

 

문제262.

워드클라우드를 그리는 함수를 Text_mining() 클래스에 포함시켜서

아래와 같이 실행되게 하시오

 

tm=Text_mining()

tm.word_paint()

 

워드 클라우드를 그릴 텍스트를 입력하세요 ~ ladaybug3.txt

 

 

class Text_mining:

   

    def word_paint(self):

        from wordcloud import WordCloud, STOPWORDS      # 워드 클라우딩 모듈

        import matplotlib.pyplot as plt                 # 시각화 모듈

        from os import path                             # 텍스트 파일을 불러오기 위한 open, path 하기 위해 os 임포트

        import re

       

        a=input('워드 클라우드를 그릴 텍스트를 입력하세요~')

       

        d = path.dirname("d://")                        # 텍스트 파일이 있는 상위 디렉토리를 path로 지정

        text = open(path.join(d, "%s"%a), mode="r", encoding="UTF-8").read()     # 텍스트파일을 open 하는데 reading만 되게 (mode="r"), UTF-8 방식으로 불러옴(UTF-8)

       

        text = re.sub("있다",'',text)

        text = re.sub("있는",'',text)

        text = re.sub("하지만",'',text)

        text = re.sub("것이다",'',text)

        text = re.sub("대한",'',text)

        text = re.sub("통해",'',text)

        text = re.sub("함께",'',text)

        text = re.sub("인공지능",'',text)

       

        text = re.sub("hani",'',text)

        text = re.sub("한다",'',text)

        text = re.sub("하는",'',text)

        text = re.sub("위해",'',text)

        text = re.sub("co",'',text)

        text = re.sub("kr",'',text)

        text = re.sub("위한",'',text)

        text = re.sub("했다",'',text)

        text = re.sub("같은",'',text)

        text = re.sub("것은",'',text)

       

       

        wordcloud = WordCloud(font_path='C://Windows//Fonts//BMHANNA_11yrs_ttf',           # 폰트 위치(거의 기본적으로 C://Windows//Fonts 안에 들어있습니다)

                              stopwords=STOPWORDS, background_color='white',        # STOPWORDS 옵션은 공백/줄바꾸기 기준으로 단어를 추출해 냅니다

                              width=1000,                                           # background_color는 워드클라우드 배경색을 나타냅니다. 'black'으로하면 검은색이 됩니다.

                              height=800,                                           # width와 height는 워드클라우드의 크기를 지정해 줍니다.

                              colormap='jet').generate(text)                       # colormap은 워드 색깔을 지정해주는데 첨부한 색감표를 사용하시면 됩니다. generate() 메소드는

       

       

        plt.figure(figsize=(13,13))                                                 # matplotlib의 pyplot을 figsize로 생성합니다

        plt.imshow(wordcloud)                                                       # 워드 클라우드 이미지를 pyplot에 띄웁니다

        plt.axis("off")                                                             # pyplot에 x, y축 표시를 없앱니다.

        plt.show()

 

tm=Text_mining()

tm.word_paint()

 

-------------

init!!!!!!!!!!!!써서!!!!!!!!!!!!

   

 

class Text_mining:

   

    def __init__(self):

        self.a=input('워드 클라우드를 그릴 텍스트를 입력하세요~')

   

    def word_paint(self):

        from wordcloud import WordCloud, STOPWORDS      # 워드 클라우딩 모듈

        import matplotlib.pyplot as plt                 # 시각화 모듈

        from os import path                             # 텍스트 파일을 불러오기 위한 open, path 하기 위해 os 임포트

        import re

       

       

       

        d = path.dirname("d://")                        # 텍스트 파일이 있는 상위 디렉토리를 path로 지정

        text = open(path.join(d, "%s"%self.a), mode="r", encoding="UTF-8").read()     # 텍스트파일을 open 하는데 reading만 되게 (mode="r"), UTF-8 방식으로 불러옴(UTF-8)

       

        text = re.sub("있다",'',text)

        text = re.sub("있는",'',text)

        text = re.sub("하지만",'',text)

        text = re.sub("것이다",'',text)

        text = re.sub("대한",'',text)

        text = re.sub("통해",'',text)

        text = re.sub("함께",'',text)

        text = re.sub("인공지능",'',text)

       

        text = re.sub("hani",'',text)

        text = re.sub("한다",'',text)

        text = re.sub("하는",'',text)

        text = re.sub("위해",'',text)

        text = re.sub("co",'',text)

        text = re.sub("kr",'',text)

        text = re.sub("위한",'',text)

        text = re.sub("했다",'',text)

        text = re.sub("같은",'',text)

        text = re.sub("것은",'',text)

       

       

        wordcloud = WordCloud(font_path='C://Windows//Fonts//BMHANNA_11yrs_ttf',           # 폰트 위치(거의 기본적으로 C://Windows//Fonts 안에 들어있습니다)

                              stopwords=STOPWORDS, background_color='white',        # STOPWORDS 옵션은 공백/줄바꾸기 기준으로 단어를 추출해 냅니다

                              width=1000,                                           # background_color는 워드클라우드 배경색을 나타냅니다. 'black'으로하면 검은색이 됩니다.

                              height=800,                                           # width와 height는 워드클라우드의 크기를 지정해 줍니다.

                              colormap='jet').generate(text)                       # colormap은 워드 색깔을 지정해주는데 첨부한 색감표를 사용하시면 됩니다. generate() 메소드는

       

       

        plt.figure(figsize=(13,13))                                                 # matplotlib의 pyplot을 figsize로 생성합니다

        plt.imshow(wordcloud)                                                       # 워드 클라우드 이미지를 pyplot에 띄웁니다

        plt.axis("off")                                                             # pyplot에 x, y축 표시를 없앱니다.

        plt.show()

 

tm=Text_mining()

tm.word_paint()

 

 

 

 

 

 

 

문제263.

Text_mining() 클래스에 있는 기능을 쉽게 이용할 있도록

메뉴를 선택하게끔

아래의 스크립트를 활용하시오

 

1. 워드클라우드를 그리려면 1번을 누르세요

2. 스크립트에서 단어를 검색하려면 2번을 누르세요

3. 스크립트에서 긍정단어의 갯수를 알려면 3번을 누르세요

4. 스크립트에서 부정단어의 갯수를 알려면 4번을 누르세요

 

숫자 1 입력하고

엔터를 치면

워드 클라우드를 그릴 텍스트를 입력하세요~ ladybug3.txt

 

 

참고코드

def print_menu():

    print("1. 워드 클라우드")

    print("2. 스크립트에서 단어를 검색")

    print("3. 스크립트에서 긍정단어 갯수 검색")

    print("4. 스크립트에서 부정단어 갯수 검색")

    menu = input("메뉴선택: ")

    return int(menu)

 

def run():

    while 1:

        menu = print_menu()   # 함수를 menu 넣는다.

        if menu == 1:

            import text_mining

     tm   

 

run()

 

 

-또는

def print_menu():

    print("1. 워드클라우드를 그릴려면 1번을 누르세요.")

    print("2. 스크립트에서 단어를 검색하려면 2번을 누르세요.")

    print("3. 스크립트에서 긍정단어의 갯수를 알려면 3번을 누르세요.")

    print("4. 스크립트에서 부정단어의 갯수를 알려면 4번을 누르세요.")

    print("5. 종료")

    menu = input("메뉴선택 : ")

    return int(menu)

 

def run():

    import Text_mining

    tm = Text_mining.Text_mining()

    while 1:

        menu = print_menu()

        if menu == 1:

            tm.word_cloud()

        if menu == 2:

            tm.find_word()

        if menu == 3:

            tm.p_count()

        if menu == 4:

            tm.n_count()

        if menu == 5:

            break

 

run()

--------------------------------------------------------------------------

반장코드

 

class Text_mining:

    def __init__(self):

        self.script = input( 'input file name : ')

       

    def find_word(self):

        from time import sleep       

        search_word = input( 'input word      : ')      

        file = open("d:\\%s" %self.script, 'r')

        sum=0

        for winter_list in file:

            a = winter_list.split(' ')

            for b in a:

                sum += b.lower().count(search_word)

                msg = '\r %d' %sum

            print(msg, end = '')

            sleep(0.000001)

           

    def positive_word(self):

        import re

        file = open('d:\\positive-words.txt','r')

        sum = 0

        p_list = []

        for positive_list in file:

            a = positive_list.split(' ')

            for b in a:

                p_list.append( re.sub('\n', '', b).lower() )

        return p_list

 

    def negative_word(self):

        import re

        file = open('d:\\negative-words.txt','r')

        sum = 0

        n_list = []

        for negative_list in file:

            a = negative_list.split(' ')

            for b in a:

                n_list.append( re.sub('\n', '', b).lower() )

        return n_list

   

    def p_count(self):

        import re

        file = open('d:\\%s'%self.script,'r')

        p_sum = 0

        p_list2 = self.positive_word()

        for winter_list in file:

            a = winter_list.split(' ')

            for b in a:

                if re.sub('[^A-z]', '', b).lower() in p_list2:

                    p_sum = p_sum + 1

        print(p_sum)

   

    def n_count(self):

        import re

        file = open('d:\\%s'%self.script,'r')

        n_sum = 0

        n_list2 = self.negative_word()

        for winter_list in file:

            a = winter_list.split(' ')

            for b in a:

                if re.sub('[^A-z]', '', b).lower() in n_list2:

                    n_sum = n_sum + 1

        print(n_sum)

       

    def word_cloud(self):

        from wordcloud import WordCloud, STOPWORDS

        import matplotlib.pyplot as plt

        from os import path

        d = path.dirname("d://")

        text = open(path.join(d, "%s"%self.script), mode="r", encoding="UTF-8").read()

        text = re.sub("있다",'',text)

        text = re.sub("있는",'',text)

        text = re.sub("하지만",'',text)

        text = re.sub("것이다",'',text)

        text = re.sub("대한",'',text)

        text = re.sub("통해",'',text)

        text = re.sub("함께",'',text)

        text = re.sub("인공지능",'',text)

        text = re.sub("hani",'',text)

        text = re.sub("한다",'',text)

        text = re.sub("하는",'',text)

        text = re.sub("위해",'',text)

        text = re.sub("co",'',text)

        text = re.sub("kr",'',text)

        text = re.sub("위한",'',text)

        text = re.sub("했다",'',text)

        text = re.sub("같은",'',text)

        text = re.sub("것은",'',text)

        wordcloud = WordCloud(font_path='C://Windows//Fonts//BMHANNA_11yrs',

                              stopwords=STOPWORDS, background_color='white',

                              width=600,                     

                              height=500,                  

                              colormap='jet').generate(text)

        plt.figure(figsize=(13,13))

        plt.imshow(wordcloud)

        plt.axis("off")

        plt.show()

 -------------------------

하나더

class Text_mining:

   

    def __init__(self):

        self.a=input('입력할 스크립트를 쓰세요 ')

   

    def print_menu(self):

        print("1. 워드 클라우드")

        print("2. 스크립트에서 단어를 검색")

        print("3. 스크립트에서 긍정단어 갯수 검색")

        print("4. 스크립트에서 부정단어 갯수 검색")

        print("5. 종료하려면 5를 누르시오")

        menu = input("메뉴선택: ")

        return int(menu)

   

 

    def run(self):

        while 1:

            menu = self.print_menu()   #위 함수를 menu에 넣는다.

            if menu == 1:

                self.word_paint()

               

               

            elif menu==2:

                print(self.find_word())

               

               

            elif menu==3:

                print(self.positive_word())

               

            elif menu==4:

                print(self.negative_word())

           

            elif menu==5:

                break

                  

   

   

 

    def find_word(self):

        import re

       

        file = open("d:\\%s"%self.a,'r')

        sum = 0

        p_list2 = self.positive_word()

        for  winter_list  in  file:

            a = winter_list.split(' ')

            for  b  in  a:

                if re.sub('[^A-z]','',b).lower() in p_list2:

                    sum = sum + 1

        return (sum)

   

   

    def positive_word(self):

        import re

        file = open("d:\\positive-words.txt",'r')

        p_list =[]

        for  winter_list  in  file:

            a = winter_list.split(' ')

            for  b  in  a:

                p_list.append( re.sub('\n','',b).lower() )

        return  p_list

 

 

   

    def nagative_word(self):

        import re

        file = open("d:\\negative-words.txt",'r')

        n_list =[]

        for  winter_list  in  file:

            a = winter_list.split(' ')

            for  b  in  a:

                n_list.append( re.sub('\n','',b).lower() )

        return  n_list

           

   

     def p_count(self):

        import re

        file = open("d:\\winter.txt",'r')

        sum = 0

        p_list2 = self.positive_word()

        for  winter_list  in  file:

            a = winter_list.split(' ')

            for  b  in  a:

                if re.sub('[^A-z]','',b).lower() in p_list2:

                    sum = sum + 1

        print (sum)

      

    def n_count(self):

        import re

        file = open("d:\\winter.txt",'r')

        sum = 0

        n_list2 = self.negative_word()

        for  winter_list  in  file:

            a = winter_list.split(' ')

            for  b  in  a:

                if re.sub('[^A-z]','',b).lower() in n_list2:

                    sum = sum + 1

        print (sum)

 

   

   

   

    def word_paint(self):

       

        from wordcloud import WordCloud, STOPWORDS      # 워드 클라우딩 모듈

        import matplotlib.pyplot as plt                 # 시각화 모듈

        from os import path                             # 텍스트 파일을 불러오기 위한 open, path 하기 위해 os 임포트

        import re

       

       

       

        d = path.dirname("d://")                        # 텍스트 파일이 있는 상위 디렉토리를 path로 지정

        text = open(path.join(d, "%s"%self.a), mode="r", encoding="UTF-8").read()     # 텍스트파일을 open 하는데 reading만 되게 (mode="r"), UTF-8 방식으로 불러옴(UTF-8)

       

        text = re.sub("있다",'',text)

        text = re.sub("있는",'',text)

        text = re.sub("하지만",'',text)

        text = re.sub("것이다",'',text)

        text = re.sub("대한",'',text)

        text = re.sub("통해",'',text)

        text = re.sub("함께",'',text)

        text = re.sub("인공지능",'',text)

       

        text = re.sub("hani",'',text)

        text = re.sub("한다",'',text)

        text = re.sub("하는",'',text)

        text = re.sub("위해",'',text)

        text = re.sub("co",'',text)

        text = re.sub("kr",'',text)

        text = re.sub("위한",'',text)

        text = re.sub("했다",'',text)

        text = re.sub("같은",'',text)

        text = re.sub("것은",'',text)

       

       

        wordcloud = WordCloud(font_path='C://Windows//Fonts//BMHANNA_11yrs_ttf',           # 폰트 위치(거의 기본적으로 C://Windows//Fonts 안에 들어있습니다)

                              stopwords=STOPWORDS, background_color='white',        # STOPWORDS 옵션은 공백/줄바꾸기 기준으로 단어를 추출해 냅니다

                              width=1000,                                           # background_color는 워드클라우드 배경색을 나타냅니다. 'black'으로하면 검은색이 됩니다.

                              height=800,                                           # width와 height는 워드클라우드의 크기를 지정해 줍니다.

                              colormap='jet').generate(text)                       # colormap은 워드 색깔을 지정해주는데 첨부한 색감표를 사용하시면 됩니다. generate() 메소드는

       

       

        plt.figure(figsize=(13,13))                                                 # matplotlib의 pyplot을 figsize로 생성합니다

        plt.imshow(wordcloud)                                                       # 워드 클라우드 이미지를 pyplot에 띄웁니다

        plt.axis("off")                                                             # pyplot에 x, y축 표시를 없앱니다.

        plt.show()

 

tm=Text_mining()

#tm.word_paint()

tm.run()

 

      

*솔루션을 구현하기 위해서 저축해야하는 핵심 엔진 코드

  1. text_mining()  클래스

  2. 스크롤링 코드

  3. 머신러닝 클래스

 

 

 


728x90
반응형

'python' 카테고리의 다른 글

18. isalpha, isdigit, 특수문자  (0) 2019.03.25
17. comprehension  (0) 2019.03.25
15-2. 특정위치 문자열(count,find)  (0) 2019.03.25
15-1. round, filter, type변환하기  (0) 2019.03.25
★판다스공식  (0) 2019.03.25