Ruser

bbc dataset 기초 통계 본문

Python/분석

bbc dataset 기초 통계

swub 2019. 6. 25. 09:32
textmining

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]:
['business', 'entertainment', 'politics', 'README.TXT', 'sport', 'tech']
  • 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]:
['business', 'entertainment', 'politics', 'sport', 'tech']
  • 각 분야별 텍스트 파일명을 가져와서 하나의 객체 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]:
['001.txt',
 '002.txt',
 '003.txt',
 '004.txt',
 '005.txt',
 '006.txt',
 '007.txt',
 '008.txt',
 '009.txt',
 '010.txt']
  • 각 분야별로 몇개의 문서가 있는지 확인한다.
In [5]:
cat_length = {}
# 각 분야별 문서수를 저장한다.
for cat in Total_file:
    cat_length[cat] = [len(Total_file[cat])]
cat_length
Out[5]:
{'business': [510],
 'entertainment': [386],
 'politics': [417],
 'sport': [511],
 'tech': [401]}
  • 한글 폰트 해결을 위해서 컴퓨터에 폰트위치를 확인하고 원하는 폰트를 찾아서 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]:
Text(0, 0.5, '자료수')

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]:
title main
0 001 The firm, which is now one of the biggest inve...
1 002 And Alan Greenspan highlighted the US governme...
2 003 State-owned Rosneft bought the Yugansk unit fo...
3 004 Reporting its results for the three months to ...
4 005 Reports in the Wall Street Journal and the Fin...
  • 각 문서별 총 단어의 개수와 문서의 전체 길이를 구한다.
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]:
title main word_count char_count
0 001 The firm, which is now one of the biggest inve... 391 1990
1 002 And Alan Greenspan highlighted the US governme... 350 1710
2 003 State-owned Rosneft bought the Yugansk unit fo... 232 1148
3 004 Reporting its results for the three months to ... 384 1904
4 005 Reports in the Wall Street Journal and the Fin... 233 1155
  • 문서별 단어수, 길이에 따른 히스토그램
In [10]:
b_word_n = business_df['word_count']
plt.hist(b_word_n)
plt.title('문서별 단어수 히스토그램')
plt.xlabel('단어수')
plt.ylabel('문서수')
Out[10]:
Text(0, 0.5, '문서수')
In [11]:
b_char_n = business_df['char_count']
plt.hist(b_char_n)
plt.title('문서별 길이 히스토그램')
plt.xlabel('길이')
plt.ylabel('문서수')
Out[11]:
Text(0, 0.5, '문서수')
  • 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]:
['The', 'firm', 'which', 'is', 'now']
  • 불용어를 제거 하지않고 구한 단어 빈도
In [15]:
text_count = pd.Series(str(i) for i in text)
text_count = text_count.value_counts()
text_count[0:15]
Out[15]:
the     8576
to      4597
of      4071
in      3680
and     3007
a       2967
said    1584
is      1514
that    1504
for     1432
The     1387
on      1162
it      1037
has     1017
by       979
dtype: int64
  • 불용어를 제거한 후 구한 단어 빈도
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]:
['The', 'firm', 'one', 'biggest', 'investors']
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]:
said       1584
The        1387
US          581
Mr          558
year        539
would       459
also        434
market      361
company     327
growth      319
last        298
could       291
new         280
economy     278
It          272
dtype: int64
  • 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]:
['firm', 'one', 'biggest', 'investors', 'Google']
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]:
said          1584
US             581
Mr             558
year           539
would          459
also           434
market         361
company        327
growth         319
last           298
could          291
new            280
economy        278
It             272
government     259
dtype: int64

'Python > 분석' 카테고리의 다른 글

파이썬을 이용한 Iris 데이터 분석  (0) 2019.03.20