ㅁ기업에서 사용하는 데이터 분석 시각화 툴
https://www.luminoso.com/daylight
- 내가 직접 스크롤링한 데이터(csv)를 위의 사이트에 올리면 다음의 결과물을 제공해줌.
1. 해당 키워드의 긍정, 부정, 중립에 대한 가장 많은 빈도를 보이는 단어들의 순위
2. 워드 클라우드 시각화
3. 해당 키워드로 연관되는 단어들에 대한 순위
(다만 비싸고, 자꾸 프로그램에 의존하게되는 경향이 있음 = 파이썬 실력 저하, 고로 이런 툴이 있다는걸 알아만 둘 것)
문제427. 지난주 마지막 문제에 대한 긍정 단어 순위를 출력하기 위해 한국에서 만든 긍정단어집을 파이썬으로 로드하시오.
문제430. (복습문제) neg 부정단어집에 '버그'라는 단어가 있는지 확인해보세요.
# 버그 포함된 단어 찾기 for i in neg: if '버그' in i: print(i) # 또는 # 카운트 사용해서 갯수 찾기 neg.count('버그)
문제431. 웹스크롤링한 레이디 버그 게시판의 모든 글 중의 긍정 단어와 그 빈도수를 출력하시오.
# 1. 파일불러오기 positive = open("c:\\data\\pos_pol_word.txt", encoding = 'utf8') pos= set(positive.read().split('\n')) pos = list(filter((lambda x : x), pos)) # 결측치 제거 negative = open("c:\\data\\neg_pol_word.txt", encoding = 'utf8') neg= set(negative.read().split('\n')) neg = list(filter((lambda x : x), neg)) lady = open("c:\\data\\ladybug_total.txt", encoding = 'utf8') lady2 = lady.read() # 2. 데이터 프레임을 만들기 위한 딕셔너리 생성 pos_dict = {} pos_dict['word'] = [] pos_dict['cnt'] = [] # 3. 데이터 입력 for i in pos: if i in lady2: pos_dict['word'].append(i) pos_dict['cnt'].append(lady2.count(i))
문제432. 부정단어 갯수를 ladybug_neg.csv에 저장하시오.
# 1. 파일불러오기 positive = open("c:\\data\\pos_pol_word.txt", encoding = 'utf8') pos = set(positive.read().split('\n')) pos = list(filter((lambda x : x), pos)) negative = open("c:\\data\\neg_pol_word.txt", encoding = 'utf8') neg = set(negative.read().split('\n')) neg = list(filter((lambda x : x), neg)) lady = open("c:\\data\\ladybug_total.txt", encoding = 'utf8') lady2 = lady.read() # 쓰기 파일 생성 후 저장 f = open("c:\\data\\ladybug_pos.csv","w") for i in pos: if i in lady2: f.write(i+','+str(lady2.count(i))+'\n') f.close() f2 = open("c:\\data\\ladybub_neg.csv","w") for i in neg: if i in lady2: f2.write(i+','+str(lady2.count(i))+'\n') f2.close()
+) utf8로 인코딩했을 때 한글이 깨지면 utf-8-sig를 사용하면됨.
문게433. 긍정단어, 긍정단어 갯수의 순위를 출력하시오. 상위 20개만 출력
# 1. 파일불러오기 positive = open("c:\\data\\pos_pol_word.txt", encoding = 'utf8') pos= set(positive.read().split('\n')) pos = list(filter((lambda x : x), pos)) # 결측치 제거 pos.remove('정') # 특정 단어 제거 pos.remove(';') lady = open("c:\\data\\ladybug_total.txt", encoding = 'utf8') lady2 = lady.read() # 2. 데이터 프레임을 만들기 위한 딕셔너리 생성 pos_dict = {} pos_dict['word'] = [] pos_dict['cnt'] = [] # 3. 데이터 입력 for i in pos: if i in lady2: pos_dict['word'].append(i) pos_dict['cnt'].append(lady2.count(i)) # 4. 판다스 데이터 프레임 생성 import pandas as pd df_pos= pd.DataFrame(pos_dict) # 긍정단어 데이터프레임 df_pos['순위'] = df_pos['cnt'].rank(ascending = False).astype('int') df_pos[:][df_pos['순위'] <= 20].sort_values(by = ['순위'], ascending = True)
문제434. 부정단어, 부정단거 갯수와 순위를 출력하시오.
negative = open("c:\\data\\neg_pol_word.txt",encoding = 'utf8') neg= negative.read().split('\n') neg = list(filter((lambda x : x), neg)) neg.remove('해') neg.remove('화') neg.remove('ㅜ') neg.remove('ㅠ') lady = open("c:\\data\\ladybug_total.txt", encoding = 'utf8') lady2 = lady.read() neg1 = 0 f3 = open("c:\\data\\ladybug_neg.csv","w", encoding = 'utf8') for i in neg: if i in lady2: # print(i+','+str(lady2.count(i))) f3.write(i+','+str(lady2.count(i))+'\n') f3.close() import pandas as pd df_neg = pd.read_csv("c:\\data\\ladybug_neg.csv", header=None) df_neg.columns = ['word','cnt'] df_neg.sort_values(by ='cnt', ascending = False).head(20)
+) 위의 코드들 정리한 버전
# 1. 파일불러오기 positive = open("c:\\data\\pos_pol_word.txt", encoding = 'utf8') pos= set(positive.read().split('\n')) pos = list(filter((lambda x : x), pos)) # 결측치 제거 pos.remove('정') pos.remove(';') negative = open("c:\\data\\neg_pol_word.txt", encoding = 'utf8') neg= set(negative.read().split('\n')) neg = list(filter((lambda x : x), neg)) neg.remove('벌') neg.remove('해') neg.remove('화') neg.remove('ㅜ') neg.remove('ㅠ') neg.remove('ㅠㅠ ') neg.remove(':)') lady = open("c:\\data\\ladybug_total.txt", encoding = 'utf8') lady2 = lady.read() # 2. 데이터 프레임을 만들기 위한 딕셔너리 생성 pos_dict = {} pos_dict['word'] = [] pos_dict['cnt'] = [] neg_dict = {} neg_dict['word'] = [] neg_dict['cnt'] = [] # 3. 데이터 입력 for i in pos: if i in lady2: pos_dict['word'].append(i) pos_dict['cnt'].append(lady2.count(i)) for i in neg: if i in lady2: neg_dict['word'].append(i) neg_dict['cnt'].append(lady2.count(i)) # 4. 판다스 데이터 프레임 생성 import pandas as pd # df_pos= pd.DataFrame(pos_dict) # 긍정단어 데이터프레임 # df_pos['순위'] = df_pos['cnt'].rank(ascending = False).astype('int') # df_pos[:][df_pos['순위'] <= 20].sort_values(by = ['순위'], ascending = True) df_neg = pd.DataFrame(neg_dict) df_neg['순위']= df_neg['cnt'].rank(ascending = False).astype('int') df_neg[:][df_neg['순위'] <=20].sort_values(by=['순위'], ascending = True)
만약에 텍스트로 같이 보고 싶다면, ( 코드 수정 필요)
positive = open("c:\\data\\pos_pol_word.txt", encoding = 'utf8') pos= positive.read().split('\n') pos = list(filter((lambda x : x), pos)) # 결측치 제거 pos.remove('정') negative = open("c:\\data\\neg_pol_word.txt",encoding = 'utf8') neg= negative.read().split('\n') neg = list(filter((lambda x : x), neg)) neg.remove('해') neg.remove('화') neg.remove('ㅜ') neg.remove('ㅠ') neg.remove('ㅠㅠ ') neg.remove('벌') neg.remove(':)') lady = open("c:\\data\\ladybug_total.txt", encoding = 'utf8') lady2 = lady.read() pos1 = 0 neg1 = 0 f2 = open("c:\\data\\ladybug_pos.csv","w", encoding = 'utf8') # 쓰기 파일 생성 f3 = open("c:\\data\\ladybug_neg.csv","w", encoding = 'utf8') for i in pos: if i in lady2: # print(i + ','+str(lady2.count(i)) ) f2.write(i + ','+str(lady2.count(i))+'\n' ) # 파일에 쓰기 for i in neg: if i in lady2: # print(i+','+str(lady2.count(i))) f3.write(i+','+str(lady2.count(i))+'\n') f2.close() f3.close() import pandas as pd # df_pos = pd.read_csv("c:\\data\\ladybug_pos.csv", header=None) # df_pos.columns = ['word','cnt'] # df_pos.sort_values(by ='cnt', ascending = False).head(20) df_neg = pd.read_csv("c:\\data\\ladybug_neg.csv", header=None) df_neg.columns = ['word','cnt'] # df_neg.sort_values(by ='cnt', ascending = False).head(20) lady = open("c:\\data\\ladybug_total.txt", encoding = 'utf8') bug2 = lady.read().split('\n') negative = open("c:\\data\\neg_pol_word.txt",encoding = 'utf8') neg= negative.read().split('\n') neg = list(filter((lambda x : x), neg)) for k in df_neg['word'].values: print('\n["'+k+'"'+'에 관한 댓글]') for i in bug2: if i.count(k) > 0: print(i)
문제436. (점심시간 문제) 위의 코드를 수정해서 다음과 같이 출력되게 하시오.
부정어 순위 1에 해당하는 "저는"단어에 관련된 댓글
import pandas as pd df_neg = pd.read_csv("c:\\data\\ladybug_neg.csv", header=None) df_neg.columns = ['word','cnt'] # 컬럼명 설정 df_neg['순위']= df_neg['cnt'].rank(method = 'dense',ascending = False).astype('int') # 순위 컬럼 생성 df_neg = df_neg[:].sort_values(by = '순위', ascending = True) # 순위 오름차순에 따라 데이터프레임 정렬 # 분석할 텍스트 파일 다시 불러와서 엔터로 분리 lady = open("c:\\data\\ladybug_total.txt", encoding = 'utf8') lady3 = lady.read().split('\n') for i in df_neg['word'].values: a = df_neg['순위'][df_neg['word'] == i].values print('\n=====부정어 순위 %d위에 해당하는 [%s] 댓글======='%(a,i)) for j in lady3: if j.count(i) > 0: print(j)
144 웹스크롤링 실전2 (중앙일보사)
ㅇ 신문기사들을 웹 스크롤링해서 현업에서 사용하는 사례
1. 핀테크 회사 : 특정 키워드와 관련된 주식 회사들을 추천
이번달, 이번주 트랜드가 무엇인가에 대한 조사부터 시작함.
2. 신문기사 => 인공신경망 => 학습 => 스스로 기사를 쓰는 인공지능을 만듦.
or 텍스트 to speech 학습시켜서 기사를 아나운서 목소리로 읽게 만듦.
예제1. 중앙일보 홈페이지에 "인공지능"을 검색했을 때 나오는 url을 가져오시오.
https://www.joongang.co.kr/search/news?keyword=%EC%9D%B8%EA%B3%B5%EC%A7%80%EB%8A%A5
예제2. 중앙일보 홈페이지에서 "인공지능으로 검색했을 때 나오는 상세기사 url을 가져오시오.
https://www.joongang.co.kr/article/25037731
https://www.joongang.co.kr/article/25037706
https://www.joongang.co.kr/article/25037652
:
:
위처럼 일일이 사람이 url을 따오는게 아니라 BeautifulSoup 모듈을 이용해서 url 긁어오기.


기사 하나를 가져오기 위해서 html코드 확인
h2 태그에 class 이름은 headline
from bs4 import BeautifulSoup import urllib import re # 중앙일보에서 키워드 검색했을 때 나오는 페이지의 html코드 가져오기 list_url = "https://www.joongang.co.kr/search/news?keyword=%EC%9D%B8%EA%B3%B5%EC%A7%80%EB%8A%A5" # 인공지능이라 검색한 결과 url url = urllib.request.Request(list_url) f = urllib.request.urlopen(url).read().decode("utf-8") # 가져온 html을 BeautifulSoup이 인식할 수 있도록 파싱 soup = BeautifulSoup(f, "html.parser") for i in soup.find_all("h2", class_ = "headline"): print(i)

상위태그 h2태그 하위태그 a , 우리가 필요한건 a 태그에 있는 url주소임.
from bs4 import BeautifulSoup import urllib import re # 중앙일보에서 키워드 검색했을 때 나오는 페이지의 html코드 가져오기 list_url = "https://www.joongang.co.kr/search/news?keyword=%EC%9D%B8%EA%B3%B5%EC%A7%80%EB%8A%A5" # 인공지능이라 검색한 결과 url url = urllib.request.Request(list_url) f = urllib.request.urlopen(url).read().decode("utf-8") # 가져온 html을 BeautifulSoup이 인식할 수 있도록 파싱 soup = BeautifulSoup(f, "html.parser") for i in soup.find_all("h2", class_ = "headline"): for k in i.find_all('a'): print(k.get("href"))

다만, 위의 방법은 이중 for문이 돌아감. for문을 한번 쓰는 방법은 아래와 같음. 하위 태그로 바로 접근해서 for문 한 번 돌림.
from bs4 import BeautifulSoup import urllib import re # 중앙일보에서 키워드 검색했을 때 나오는 페이지의 html코드 가져오기 list_url = "https://www.joongang.co.kr/search/news?keyword=%EC%9D%B8%EA%B3%B5%EC%A7%80%EB%8A%A5" # 인공지능이라 검색한 결과 url url = urllib.request.Request(list_url) f = urllib.request.urlopen(url).read().decode("utf-8") # 가져온 html을 BeautifulSoup이 인식할 수 있도록 파싱 soup = BeautifulSoup(f, "html.parser") base = soup.select("h2.headline > a") # h2 태그의 headline 클래스> a로 접근 for i in base: print(i.get("href")) # 상세url 뽑는 코드
base = soup.selec("h2.headline > a") html코드에서 h2태그의 headline 클래스의 자식 태그인 a태그의 html문서들을 가져오라는 뜻
예제3. 위에서 출력되고 있는 상세url을 params라는 비어있는 리스트에 append 시키세요.
from bs4 import BeautifulSoup import urllib import re # 중앙일보에서 키워드 검색했을 때 나오는 페이지의 html코드 가져오기 list_url = "https://www.joongang.co.kr/search/news?keyword=%EC%9D%B8%EA%B3%B5%EC%A7%80%EB%8A%A5" # 인공지능이라 검색한 결과 url url = urllib.request.Request(list_url) f = urllib.request.urlopen(url).read().decode("utf-8") # 가져온 html을 BeautifulSoup이 인식할 수 있도록 파싱 soup = BeautifulSoup(f, "html.parser") base = soup.select("h2.headline > a") # 상세url 리스트에 담기 params = [] for i in base: params.append(i.get("href"))
예제4.https://www.joongang.co.kr/article/25037685 url의 본문기사 텍스트를 긁어오기 위해 아래의 url로 접속해서 태그명과 class명을 알아내시오.

div 태그 클래스 이름 article_body fs3 아이디 article_body
예제5. 위에서 알아낸 태그 이름과 클래스 이름을 가지고 본문기사 내용을 출력하시오.
from bs4 import BeautifulSoup import urllib import re list_url = "https://www.joongang.co.kr/article/25037731" # 해당기사 url url = urllib.request.Request(list_url) f = urllib.request.urlopen(url).read().decode("utf-8") soup2 = BeautifulSoup(f, "html.parser") for i in soup2.find_all("div", class_ = "article_body fs3"): print( i.text ) # 본문만 출력하기
print(re.sub('[\n\r\t]','',i.text))로 본문을 보기 편하게 정렬시킴.
예제6. params 리스트 안에 들어있는 상세url을 전부 받아서 기사본문을 전부 출력하시오.
from bs4 import BeautifulSoup import urllib import re # 중앙일보에서 키워드 검색했을 때 나오는 페이지의 html코드 가져오기 list_url = "https://www.joongang.co.kr/search/news?keyword=%EC%9D%B8%EA%B3%B5%EC%A7%80%EB%8A%A5" # 인공지능이라 검색한 결과 url url = urllib.request.Request(list_url) f = urllib.request.urlopen(url).read().decode("utf-8") # 가져온 html을 BeautifulSoup이 인식할 수 있도록 파싱 soup = BeautifulSoup(f, "html.parser") base = soup.select("h2.headline > a") # 상세url 리스트에 담기 params = [] for i in base[5:]: params.append(i.get("href")) for i in params: # # 상세 url for문으로 돌리기 url = urllib.request.Request(i) f = urllib.request.urlopen(url).read().decode("utf-8") soup2 = BeautifulSoup(f, "html.parser") for k in soup2.find_all("div", class_ = "article_body fs3"): print(re.sub('[\n\r\t]','',k.text))
예제7. 위에서 출력되고 있는 텍스트들을 PC에 저장하시오.
from bs4 import BeautifulSoup import urllib import re # 중앙일보에서 키워드 검색했을 때 나오는 페이지의 html코드 가져오기 list_url = "https://www.joongang.co.kr/search/news?keyword=%EC%9D%B8%EA%B3%B5%EC%A7%80%EB%8A%A5" # 인공지능이라 검색한 결과 url url = urllib.request.Request(list_url) f = urllib.request.urlopen(url).read().decode("utf-8") # 가져온 html을 BeautifulSoup이 인식할 수 있도록 파싱 soup = BeautifulSoup(f, "html.parser") base = soup.select("h2.headline > a") # 상세url 리스트에 담기 params = [] for i in base[5:-5]: params.append(i.get("href")) f2 = open("c:\\data\\joongang1.txt","w",encoding = 'utf8') cnt = 0 for i in params: # # 상세 url for문으로 돌리기 url = urllib.request.Request(i) f = urllib.request.urlopen(url).read().decode("utf-8") soup2 = BeautifulSoup(f, "html.parser") for k in soup2.find_all("div", class_ = "article_body fs3"): cnt+=1 f2.write(str(cnt) + re.sub('[\n\r\t]','',k.text)+'\n\n') f2.close()
예제8. 위에서 긁어온 기사들은 극히 일부임. 더 많은 기사들을 긁어올 수 있도록 아래로 스크롤을 내려서 더보기를 눌러 기사들을 계속 가져올 수 있도록 하시오.
이를 하기 위해서는 selenium을 이용해서 자동화 시켜줘야함.
웹페이지의 스크롤을 컴퓨터가 알아서 내리도록 하고 더보기도 컴퓨터가 알아서 클릭할 수 있도록 함.
1. 크롬 드라이버 설치
https://sites.google.com/chromium.org/driver/downloads
C:\data\chromedriver_win32\\chromedriver.exe
2. 일단 예제3번코드를 전부 가져와서 일부 수정하겠음.
from selenium import webdriver # 컴퓨터가 알아서 웹페이지를 움직이는 모듈 from bs4 import BeautifulSoup import urllib import re # 중앙일보에서 키워드 검색했을 때 나오는 페이지의 html코드 가져오기 list_url = "https://www.joongang.co.kr/search/news?keyword=%EC%9D%B8%EA%B3%B5%EC%A7%80%EB%8A%A5" # 인공지능이라 검색한 결과 url driver = webdriver.chrome("c:\\data\\chromedriver_win32\\chromedriver.exe") driver.implicitly_wait(10) driver.get(list_url) while True: try: 더보기 = driver.fine_element_by_css_selector('a.btn.btn_outline_gray') 더보기.click() except: break
문제발생 : selenium 모듈 없음 > pip 설치해야함.
ModuleNotFoundError: No module named 'selenium'
아나콘다 프롬프트 pip install selenium 설치
from selenium import webdriver # 컴퓨터가 알아서 웹페이지를 움직이는 모듈 from bs4 import BeautifulSoup import urllib import re import time # 중앙일보에서 키워드 검색했을 때 나오는 페이지의 html코드 가져오기 list_url ="https://www.joongang.co.kr/search/news?keyword=%EC%9D%B8%EA%B3%B5%EC%A7%80%EB%8A%A5" driver = webdriver.Chrome("C:\\data\\chromedriver_win32\\chromedriver.exe") driver.implicitly_wait(10) driver.get(list_url) while True: try: 더보기 = driver.find_element_by_css_selector('a.btn.btn_outline_gray') 더보기.click() time.sleep(1) except: break
대신 while문으로 돌 경우 무한루프 생성되니 가급적이면 for문으로 돌릴 것.
'Study > class note' 카테고리의 다른 글
감성분석 기본코드(한글) (0) | 2022.01.05 |
---|---|
python / 네이버 블로그 웹스크롤링 (0) | 2022.01.04 |
python / beautiful soup 모듈 (0) | 2021.12.31 |
python / HTML 기본문법 (0) | 2021.12.30 |
python / readline,write,writelines,read/write,rb/rw,with~as (0) | 2021.12.30 |