CSV 파일
Comma Separated Value
행단위를 ,(콤마)를 이용해서 구분
파이썬에서는 쉽게 CSV파일을 조작할 수 있도록 csv 모듈을 제공
CSV 파일 읽기
c:\python\data.csv
이름,국어,영어,수학,물리,지구과학
홍길동,100,90,80,22,92
길동홍,80,52,90,45,67
동홍길,56,98,33,58,70
c:\python\csv_reader.py
import csv
# 일반적인 파일 처리 방식으로 csv 파일을 처리
with open('data.csv', 'r', encoding='utf-8') as csv_file:
for line in csv_file:
data = line.strip().split(',') # 콤마(,)를 구분자(delimiter)로하여 파싱
for d in data:
print(d, end='\t')
print()
# csv 모듈을 이용한 cvs 파일 처리
with open('data.csv', 'r', encoding='utf-8') as csv_file:
csv_data = csv.reader(csv_file)
for data in csv_data:
for d in data:
print(d, end='\t')
print()
csv 파일 저장
input_data.txt
이름 국어 영어 수학 물리 지구과학
홍길동 100 90 80 22 92
길동홍 80 52 90 45 67
동홍길 56 98 33 58 70
csv_reader.py
import csv
with open('input_data.txt', 'r', encoding='utf-8') as input_txt_file, \
open('output_data.csv', 'w', newline='', encoding='utf-8') as output_csv_file:
lines = input_txt_file.readlines()
csv_format = []
for line in lines:
csv_format.append(line.strip().split())
csvobject = csv.writer(output_csv_file, delimiter='|')
csvobject.writerows(csv_format)
output_data.cvs
이름,국어,영어,수학,물리,지구과학
홍길동,100,90,80,22,92
길동홍,80,52,90,45,67
동홍길,56,98,33,58,70
csv 모듈을 이용하지 않고, 위의 과정을 구현하기
input_data.txt 파일을 읽어서 output_data.csv 파일 형식으로 출력
import csv, re
# with open('input_data.txt', 'r', encoding='utf-8') as input_txt_file, \
# open('output_data.csv', 'w', encoding='utf-8') as output_csv_file:
# lines = input_txt_file.readlines()
# csv_format = []
# for line in lines:
# print(line.strip().split())
# csv_format.append(line.strip().split())
# csvobject = csv.writer(output_csv_file, delimiter=',')
# csvobject.writerows(csv_format)
with open('input_data.txt', 'r', encoding='utf-8') as input_txt_file, \
open('output_data.csv', 'w', encoding='utf-8') as output_csv_file:
for line in input_txt_file:
datas = line.strip().split()
# 방법1. 마지막 데이터에도 불필요한 콤마가 추가되는 문제점이 있음
# for d in datas:
# output_csv_file.write('{},'.format(d))
#
# output_csv_file.write('\n')
# 방법2. 마지막 데이터를 확인하기 위해서 인덱스로 처리
for i in range(len(datas)):
output_csv_file.write('{}'.format(datas[i]))
# 마지막 데이터에는 콤마를 추가하지 않도록 처리
if i != len(datas) - 1:
output_csv_file.write(',')
output_csv_file.write('\n')
# 방법3. 파일에 쓰기전에 마지막 콤마를 제거하는 방법
# 파일에 쓸 데이터를 먼저 만드는 작업이 필요
# data_for_write = ''
# for d in datas:
# data_for_write = data_for_write + d + ','
# output_csv_file.write(data_for_write[:-1])
# output_csv_file.write('\n')
apt_data.csv 파일을 이용해서 원하는 아파트의 정보를 검색
c:\python\apt_search.py
import csv, re, os
# # https://docs.python.org/ko/3/library/os.html
# print(os.getcwd()) # 현재 작업 디렉터리 정보를 조회
# print(os.listdir()) # 현재 작업 디렉터리의 파일 리스트를 조회
# os.chdir('c:\\') # 작업 디렉터리를 변경
# print(os.getcwd())
# print(os.listdir())
os.chdir('c:\\python')
with open('apt_data.csv', 'r') as file:
apt_data = csv.reader(file)
min_apt = ''
min = 0
for apt in apt_data:
# 검색 조건을 추가
# 시군구 번지 본번 부번 단지명 전용면적(㎡) 계약년월 계약일 거래금액(만원) 층 건축년도 도로명
# 강원도 강릉시 견소동 202 202 0 송정한신 84.945 202012 3 17,000 13 1997 경강로2539번길 8
if apt[0] == '시군구':
continue
if re.search('부평', apt[0]):
if min == 0 or apt[8] < min:
min_apt = apt[4]
min = apt[8]
print('부평에서 가장 저렴한 아파트는 {} 입니다.'.format(min_apt))
실습: 인천광역시에 있는 아파트 중 전용면적 120m2 이상 거래금액 5억 이하의 아파트를 조회해서 출력 (아파트 이름, 거래 금액)
import csv, re, os
# # https://docs.python.org/ko/3/library/os.html
# print(os.getcwd()) # 현재 작업 디렉터리 정보를 조회
# print(os.listdir()) # 현재 작업 디렉터리의 파일 리스트를 조회
# os.chdir('c:\\') # 작업 디렉터리를 변경
# print(os.getcwd())
# print(os.listdir())
os.chdir('c:\\python')
with open('apt_data.csv', 'r') as file:
apt_data = csv.reader(file)
for apt in apt_data:
if apt[0] == '시군구':
continue
if re.match('인천광역시', apt[0]) and \
float(apt[5]) <= 120.0 and \
int(re.sub(',', '', apt[8])) >= 50000:
print('{}\t{}'.format(apt[4], apt[8]))
실습) 내려받은 데이터 파일을 분석 (C:\Users\myanj\Downloads\202012_202012_연령별인구현황_월간.csv)
A: 행정구역
B: 해당 기간의 총인구수
C: 해당 기간의 연령구간인구수
D~ : 해당 기간의 연령별 인구수 (0세 ~ 100세이상 ⇒ 101개의 컬럼)
해당 기간의 남자 총인구수
해당 기간의 남자 연령구간인구수
해당 기간의 남자 연령별 인구수
해당 기간의 여자 총인구수
해당 기간의 여자 연령구간인구수
해당 기간의 여자 연령별 인구수
본인 거주하고 있는 지역의 인구 현황을 출력
c:\python\age.py
import csv, re
import matplotlib.pyplot as plt
result = []
with open('C:\\Users\\myanj\\Downloads\\202012_202012_연령별인구현황_월간.csv', 'r') as file:
datas = csv.reader(file)
area = input('인구 현황을 조회할 지역 이름을 입력하세요: ')
for data in datas:
if area in data[0]: # data[0] 행정구역
for i in data[3:104]: # 0세 부터 100세이상 까지
result.append(int(i))
plt.style.use('ggplot') # 격자 무늬 안내선 스타일
# plt.bar(range(0, 101), result) # 수직 막대 그래프
plt.barh(range(0, 101), result) # 수평 박대 그래프
plt.show()
matplotlib 모듈 설치
PS C:\python> pip install matplotlib
참고 ⇒ https://matplotlib.org/contents.html
BeautifulSoup
⇒ 웹 문서를 구성하는 HTML과 XML 문서에서 원하는 정보를 쉽게 추출할 수 있는 모듈을 모아 놓은 파이썬 패키지
PS C:\python> python.exe -m pip install --upgrade pip
PS C:\python> pip install beautifulsoup4
명언 제공 사이트 ⇒ http://quotes.toscrape.com/
from bs4 import BeautifulSoup as bs
import urllib.request as req
# 웹 페이지(문서)를 가져와서 가공
url = 'http://quotes.toscrape.com/'
html = req.urlopen(url)
# 뷰티플소프를 이용해서 파싱하기 좋은 상태로 변환
soup = bs(html.read(), 'html.parser')
# soup.find_all(TAG_NAME) ==> 특정 태그(TAG_NAME)로 둘러쌓인 요소를 찾아서 리스트로 반환
head = soup.find_all("head")
#print(head, len(head))
links = soup.find_all("link")
#print(links, len(links))
# itemprop 속성 값으로 text를 가지는 span 태그를 모두 검색해서 리스트로 반환
spans = soup.find_all("span", {"itemprop": "text"})
#print(spans, len(spans))
for s in spans:
print(s.text)
실행결과
“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”
“It is our choices, Harry, that show what we truly are, far more than our abilities.”
“There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”
“The person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.”
“Imperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.”
“Try not to become a man of success. Rather become a man of value.”
“It is better to be hated for what you are than to be loved for what you are not.”
“I have not failed. I've just found 10,000 ways that won't work.”
“A woman is like a tea bag; you never know how strong it is until it's in hot water.”
“A day without sunshine is like, you know, night.”
위 명언 크롤링 기능을 실행 파일로 만들기
PS C:\python> pip install pyinstaller
PS C:\python> pyinstaller --onefile crawling.py
PS C:\python> tree /a /f
폴더 PATH의 목록입니다.
볼륨 일련 번호는 04A2-8BD4입니다.
C:.
| age.py
| apt_data.csv
| apt_searach.py
| crawing.spec
| crawling.py
| crawling.spec
| csv_reader.py
| csv_writer.py
| data.csv
| excel_data.zip
| input.txt
| input_data.txt
| new_crawling.spec
| output.txt
| test.py
|
+---.vscode
| launch.json
|
+---build
| +---crawing
| +---crawling
:
| |
| \---new_crawling
+---dist
| crawling.exe ⇐ pyinstaller 를 이용해서 생성한 실행 파일
|
+---excel_data
| | [Content_Types].xml
| |
| +---docProps
| | app.xml
| | core.xml
| |
| +---xl
| | | sharedStrings.xml
| | | styles.xml
| | | workbook.xml
| | |
| | +---printerSettings
| | | printerSettings1.bin
| | |
| | +---theme
| | | theme1.xml
| | |
| | +---worksheets
| | | | sheet1.xml
| | | |
| | | \---_rels
| | | sheet1.xml.rels
| | |
| | \---_rels
| | workbook.xml.rels
| |
| \---_rels
| .rels
|
\---__pycache__
crawling.cpython-39.pyc
PS C:\python> cd dist
PS C:\python\dist> .\crawling.exe
“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”
“It is our choices, Harry, that show what we truly are, far more than our abilities.”
“There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”
“The person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.”
“Imperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.”
“Try not to become a man of success. Rather become a man of value.”
“It is better to be hated for what you are than to be loved for what you are not.”
“I have not failed. I've just found 10,000 ways that won't work.”
“A woman is like a tea bag; you never know how strong it is until it's in hot water.”
“A day without sunshine is like, you know, night.”