import xlrd
import xlwt
# 엑셀 파일 읽기 함수
def load_excel_data(file_path):
# 파일 열기 객체 생성
workbook = xlrd.open_workbook(file_path)
worksheet = workbook.sheet_by_index(0)
# 데이터 저장소 초기화
educational_institutions = []
# 모든 행 순회
for row_idx in range(worksheet.nrows):
institution = []
# 모든 열 순회
for col_idx in range(worksheet.ncols):
cell_content = worksheet.cell_value(row_idx, col_idx)
institution.append(cell_content)
educational_institutions.append(institution)
return educational_institutions
# 엑셀 파일 쓰기 함수
def save_excel_data(institutions):
# 새 워크북 생성
output_workbook = xlwt.Workbook(encoding='utf-8')
# 워크시트 추가
data_sheet = output_workbook.add_sheet('상하이시 고등교육기관 정보')
# 텍스트 스타일 설정
title_font = xlwt.Font()
title_font.bold = True
title_font.height = 400
title_font.underline = True
title_font.colour_index = 6
alignment = xlwt.Alignment()
alignment.horz = 2 # 가운데 정렬
alignment.vert = 1 # 수직 중앙 정렬
style = xlwt.XFStyle()
style.font = title_font
style.alignment = alignment
# 제목 셀 병합 및 작성
data_sheet.write_merge(0, 0, 0, 6, '상하이시 고등교육기관 정보', style)
# 헤더 작성
for col in range(7):
data_sheet.write(1, col, institutions[0][col])
# 데이터 작성 (상하이시에 위치한 기관만)
current_row = 2
for institution in institutions:
if institution[2] == '상하이시':
for col in range(7):
data_sheet.write(current_row, col, institution[col])
current_row += 1
# 파일 저장
output_workbook.save('../R&Q_pic/상하이시 고등교육기관 정보.xls')
# 데이터 처리 실행
school_data = load_excel_data('../Stu_pack/wordcloud/school.xls')
save_excel_data(school_data)
# 결과 확인
result_data = load_excel_data('../R&Q_pic/상하이시 고등교육기관 정보.xls')
counter = 1
for institution in result_data:
if counter < 13:
print(institution)
counter += 1
판다스(Pandas)를 이용한 엑셀 파일 처리
import pandas as pd
# 엑셀 파일 읽기
excel_data = pd.read_excel('../Stu_pack/wordcloud/school.xls')
# 데이터 미리보기 (기본 5개 행)
excel_data.head(10)
# 데이터 끝부분 미리보기 (마지막 10개 행)
excel_data.tail(10)
# 특정 지역(상하이시) 데이터 필터링
shanghai_institutions = excel_data[excel_data["所在省份"] == "상하이시"]
# 필터링된 데이터 저장
shanghai_institutions.to_excel('../R&Q_pic/상하이시 고등교육기관 정보.xlsx')
워드클라우드(Wordcloud) 라이브러리 설치 및 활용
1. 설치
# 네트워크를 통한 설치
pip install wordcloud
# 로컬 파일을 통한 설치
python -m pip install 로컬_경로
2. 활용 방법
워드클라우드 생성 절차:
- 워드클라우드 객체 생성
- 텍스트 데이터 로드
- 워드클라우드 이미지 출력
예시 1: 기본 사각형 워드클라우드 생성
import wordcloud
from PIL import Image
# 텍스트 파일 읽기
with open('../Stu_pack/wordcloud/만강.txt', encoding='utf-8') as text_file:
text_content = text_file.read()
# 텍스트 분할 및 재조합
processed_text = ' '.join(jieba.lcut(text_content))
# 워드클라우드 객체 생성
wc = wordcloud.WordCloud(font_path='C:\Windows\Fonts\STHUPO.TTF')
# 텍스트 로드
wc.generate(text_content)
# 이미지 파일로 저장
wc.to_file('../R&Q_pic/test.jpg')
Image.open('../R&Q_pic/test.jpg')
예시 2: 사용자 지정 모양 워드클라우드 생성
import wordcloud
from PIL import Image
from imageio import imread
# 텍스트 파일 읽기
with open('../Stu_pack/wordcloud/만강.txt', encoding='utf-8') as text_file:
text_content = text_file.read()
# 텍스트 분할 및 재조합
processed_text = ' '.join(jieba.lcut(text_content))
# 마스크 이미지 로드
mask_image = imread('../Stu_pack/wordcloud/Five_Star.PNG')
# 워드클라우드 객체 생성 (마스크 적용)
wc = wordcloud.WordCloud(
mask=mask_image,
font_path='C:\Windows\Fonts\STHUPO.TTF',
background_color='#ff00cc'
)
# 텍스트 로드
wc.generate(text_content)
# 이미지 파일로 저장
wc.to_file('../R&Q_pic/test.jpg')
Image.open('../R&Q_pic/test.jpg')