Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 연금재정방식이론
- 일반수학
- 문제풀이
- 도달연령방식
- 보험수학
- 연금수리학
- 표준부담금
- 사외적립자산
- 근로자퇴직여법
- 기초율산정
- 연금수리개관
- 연금채무
- 보험계리사
- 확률과 통계
- 연금수리
- 현재단위적립방식
- 종합보험료방식
- 최신연금수리학
- 예측단위적립방식
- 종합가입보험료방식
- 중급회계
- 보험수리적손익
- 계리적손익
- 초기채무동결방식
- 가입연령방식
- 개인평준보험료방식
- 계리가치
- 공적연금재정방식
- IFRS 17
- LDI
Archives
- Today
- Total
Ruser
bbc dataset 기초 통계 본문
bbc dataset의 기초 통계¶
- bbc dataset은 2004년부터 2005년까지 5개 분야의 bbc 뉴스 웹사이트에서 나온 2225개의 문서이다.
- 5개 분야: business, entertainment, politics, sport, tech
In [1]:
# 특정 파일의 하위 파일 목록을 가져오기 위한 패키지
import os
# 여러 통계 그래프를 그리기 위한 패키지
import matplotlib
import matplotlib.pyplot as plt
# python에서 dataframe을 사용하기 위한 패키지
import pandas as pd
# 그래프 사이즈 조절을 위한 패키지
from pylab import rcParams
# 불용어 제거 및 단어 스플릿을 위한 패키지
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
# 정규표현식을 사용하기 위한 패키지
import re
bbc dataset의 각 분야별 문서 가져오기¶
- bbc dataset은 bbc 파일의 하위 파일로 분야가 나누어져있고 그 아래에 각 분야별 텍스트 자료들이 포함되어 있다.
- 먼저 각 분야의 파일위치를 확인한다.
In [2]:
# bbc 경로
path_dir = 'C:/Users/stat/Downloads/bbc-full-text-document-classification/bbc'
file_list_new = []
# bbc의 하위 파일 목록을 가져오기
file_list = os.listdir(path_dir)
file_list
Out[2]:
- bbc 파일의 하위 파일에는 bbc dataset을 설명하는 README.TXT 파일이 포함되어 있어 이를 제외한 나머지를 가져온다.
In [3]:
# file_list 중 카테고리가 아닌 파일(README.TXT) 제거
# 조건: item.find(".TXT")를 하였을때 값이 -1 인 경우만 다음 실행
for item in file_list:
if item.find('.TXT') is -1:
file_list_new.append(item)
file_list_new
Out[3]:
- 각 분야별 텍스트 파일명을 가져와서 하나의 객체 Total_file(dict) 에 저장한다.
In [4]:
# 각 분야별로 텍스트 파일명을 받을 dictionary 생성
Total_file = {}
# 각 분야의 하위 파일 목록 가져오기
for category in file_list_new:
Total_file[category] = os.listdir(path_dir + '/' + str(category))
# Total_file(dict) 중 business의 첫번째 부터 열번째 데이터 보기
Total_file['business'][0:10]
Out[4]:
- 각 분야별로 몇개의 문서가 있는지 확인한다.
In [5]:
cat_length = {}
# 각 분야별 문서수를 저장한다.
for cat in Total_file:
cat_length[cat] = [len(Total_file[cat])]
cat_length
Out[5]:
- 한글 폰트 해결을 위해서 컴퓨터에 폰트위치를 확인하고 원하는 폰트를 찾아서 matplotlib에 폰트를 적용시켜준다.
In [6]:
font_location = "C:/Windows/Fonts/malgunbd.ttf"
font_name = matplotlib.font_manager.FontProperties(fname = font_location).get_name()
matplotlib.rc("font", family = font_name)
In [7]:
# 그래프의 사이즈를 조정
rcParams['figure.figsize'] = 15, 5
# barplot을 그리기위해 cat_length를 dataframe형식으로 변환한다.
cat_length_df = pd.DataFrame.from_dict(cat_length)
# barplot 그림
cat_length_df.plot.bar()
plt.title('분야별 자료수')
plt.xlabel('분야')
plt.ylabel('자료수')
Out[7]:
business 텍스트 자료분석¶
- business의 문서를 파일명으로 넘버링을하고 본문 내용을 가지고 온다.
In [8]:
business = {}
title = []
main = []
for file in Total_file['business']:
text = open(path_dir + '/' + str('business') + '/' + str(file), 'r')
text = text.read()
# 뉴스본문만 가져감
text = text.split('\n\n', 2)
m = text[-1]
# 뉴스본문의 \n 제거
m = m.replace("\n", "")
# 뉴스 넘버
title.append(str(file.replace(".txt", "")))
# 뉴스 본문
main.append(m)
# 뉴스 제목과 뉴스 본문으로 이루어진 dict
business['title'] = title
business['main'] = main
# 데이터프레임으로 변환
business_df = pd.DataFrame.from_dict(business)
business_df.head()
Out[8]:
- 각 문서별 총 단어의 개수와 문서의 전체 길이를 구한다.
In [9]:
# 구분자가 없는경우 스페이스를 기준으로 스플릿된 단어들의 개수
business_df['word_count'] = business_df['main'].apply(lambda x : len(x.split()))
# 공백을 제외한 나머지 단어들의 총 길이
business_df['char_count'] = business_df['main'].apply(lambda x : len(x.replace(" ","")))
business_df.head()
Out[9]:
- 문서별 단어수, 길이에 따른 히스토그램
In [10]:
b_word_n = business_df['word_count']
plt.hist(b_word_n)
plt.title('문서별 단어수 히스토그램')
plt.xlabel('단어수')
plt.ylabel('문서수')
Out[10]:
In [11]:
b_char_n = business_df['char_count']
plt.hist(b_char_n)
plt.title('문서별 길이 히스토그램')
plt.xlabel('길이')
plt.ylabel('문서수')
Out[11]:
- business 분야의 전체 단어 출연 빈도 구하기
In [12]:
# 방법 1 그냥 해본 방법
#text = " ".join(business_df.main)
#text = text.split(" ")
#text[0:5]
In [13]:
# 방법 2 패키지 활용
# business의 문서 본문전체를 하나로 합친다.
text = " ".join(business_df.main)
# text에서 영문과 숫자와 스페이스를 제외한 나머지를 다 공백으로 치환한다.
english = re.compile('[^a-zA-Z0-9 ]+')
text = english.sub('', text)
In [14]:
text = word_tokenize(text)
text[0:5]
Out[14]:
- 불용어를 제거 하지않고 구한 단어 빈도
In [15]:
text_count = pd.Series(str(i) for i in text)
text_count = text_count.value_counts()
text_count[0:15]
Out[15]:
- 불용어를 제거한 후 구한 단어 빈도
In [16]:
stop_words = set(stopwords.words('english'))
text_new = [w for w in text if not w in stop_words]
text_new[0:5]
Out[16]:
In [17]:
text_count_new = pd.Series(str(i) for i in text_new)
text_count_new = text_count_new.value_counts()
text_count_new[0:15]
Out[17]:
- the는 불용어사전에 포함되어있지만 The는 불용어 처리가 되지않아 The 도 불용어 사전에 포함 시킨 후 다시 실행
In [18]:
stop_words.update({'The'})
text_new = [w for w in text if not w in stop_words]
text_new[0:5]
Out[18]:
In [19]:
text_count_new = pd.Series(str(i) for i in text_new)
text_count_new = text_count_new.value_counts()
text_count_new[0:15]
Out[19]:
'Python > 분석' 카테고리의 다른 글
파이썬을 이용한 Iris 데이터 분석 (0) | 2019.03.20 |
---|