파일 다운로드
파일 열기
파일 → 다른 이름으로 저장 → CSV(쉼표로 분리) 선택 후 → 파일명 입력
엑셀 종료 후 notepad로 열어보기
line_counter = 0 # 파일의 총 줄 수를 세는 변수
data_header = [] # data의 필드값을 저장하는 list
customer_list = [] # customer 개별 list를 저장하는 list
with open("customers.csv") as customer_data: # customer.csv 파일을 customer_data 객체에 저장
while True:
data = customer_data.readline() # customer.csv에 한 줄씩 data 변수에 저장
if not data: break # 데이터가 없을 때 loop 종료
if line_counter == 0: # 첫 번째 데이터는 데이터의 필드
data_header = data.split(".") # 데이터 필드는 data_header list에 저장, 데이터 저장시 ","로 분리
else:
customer_list.append(data.split(",")) # 일반 데이터는 customer_list 객체에 저장, 데이터 저장시 ","로 분리
line_counter += 1
print("Header :\t", data_header) # 데이터 필드값 출력
for i in range(10): # 데이터 출력 (샘플 10개만)
print("Data", i, ":\t\t", customer_list[i])
print(len(customer_list)) # 전체 데이터 크기 출력
line_counter = 0 # 파일의 총 줄 수를 세는 변수
data_header = [] # data의 필드값을 저장하는 list
employee = []
customer_USA_only_list = [] # customer 개별 list를 저장하는 list
customer = None
with open("customers.csv", "r") as customer_data: # customer.csv 파일을 customer_data 객체에 저장
while True:
data = customer_data.readline() # customer.csv에 한 줄씩 data 변수에 저장
if not data: break # 데이터가 없을 때 loop 종료
if line_counter == 0: # 첫 번째 데이터는 데이터의 필드
data_header = data.split(".") # 데이터 필드는 data_header list에 저장, 데이터 저장시 ","로 분리
else:
customer = data.split(",")
if customer[10].upper() == "USA": # customer 데이터의 offset 10번째 필드값
customer_USA_only_list.append(customer) # country 필드가 "USA"인 것만
line_counter += 1
print("Header :\t", data_header) # 데이터 필드값 출력
for i in range(10): # 데이터 출력 (샘플 10개만)
print("Data", i, ":\t\t", customer_USA_only_list[i])
print(len(customer_USA_only_list)) # 전체 데이터 크기 출력
with open("customers_USA_only.csv", "w") as customer_USA_only_csv:
for customer in customer_USA_only_list:
customer_USA_only_csv.write(",".join(customer).strip('\n') + '\n')
csv
객체로 CSV 처리import csv
goyang_data = []
header = []
row_num = 0
with open("korea_foot_traffic_data.csv", "r", encoding="utf8") as p_file:
csv_data = csv.reader(p_file) # csv 객체 이용해 csv_data 읽기
for row in csv_data: # 읽어온 데이터 한 줄씩 처리
if row_num == 0:
header = row # 첫 번째 줄은 데이터 필드로 따로 저장
location = row[7] # '행정구역' 필드 데이터 추출, 한글 처리로 유니코드 데이터를 utf8로 변환
if location.find(u"고양시") != -1:
goyang_data.append(row) # '행정구역' 데이터에 성남시가 들어가 있으면 seoungnam_data list에 추가
row_num += 1
with open("goyang_foot_traffic_data.csv", "w", encoding="utf8") as g_p_file:
writer = csv.writer(g_p_file, delimiter='\t', quotechar="'", quoting=csv.QUOTE_ALL)
# csv.writer를 사용해서 csv 파일 만들기
# delimiter: 필드 구분자, quotechar: 필드의 각 데이터를 묶는 문자, quoting: 묶는 범위
writer.writerow(header)
for row in goyang_data:
writer.writerow(row)
,
’ 등에 대해 전처리 필요csv
객체를 제공<title> Hello, World </title>
→ 제목 요소, 값은 Hello, World<!doctype html>
<html>
<head>
<title> Hello HTML </title>
</head>
<body>
<p>Hello WOrld!</p>
</body>
</html>
<html>
- <head>
- <title>
- <body>
- <p>
<tag attribute1=”att_value1” attrigute2=”att_value1”> 보이는 내용(Value) </tag>
^\d{3}\-\d{4}\-\d{4}$
^\d{1, 3}\.\d{1, 3}\.\d{1, 3}\.\d{1, 3}$
^[a-zA-Z0-9]+@[a-zA-Z0-9]+$
또는 ^[_0-9a-zA-Z-]+@[0-9a-zA-Z-]+(.[_0-9a-zA-Z-]+)*$
^01(?:0|1|[6-9])-(?:\d{3}|\d{4})-\d{4}$
\d{6} \- [1-4]\d{6}
([0-9]{1,3}) \. ([0-9]{1,3} \. ([0-9]{1,3}) \. ([0-9]{1,3})
정규표현식(Regular Expression)을 소개합니다.
[]
: [
와 ]
사이의 문자들과 매치라는 의미[abc]
← 해당 글자에 a, b, c 중 하나가 있음-
”를 이용해 범위를 지정할 수 있음[a-zA-Z]
→ 알파벳 전체, [0-9]
→ 숫자 전체.
^
$
*
+
?
{
}
[
]
\
|
(
)
.
: 줄바꿈 문자인 \n
을 제외한 모든 문자와 매치*
: 앞에 있는 글자가 반복해서 나올 수 있음+
: 앞에 있는 글자가 최소 1회 이상 반복{m.n}
: 반복 횟수를 지정?
: 반복 횟수가 1회|
: orimport re
import urllib.request
url = "http://goo.gl/U7mSQl"
html = urllib.request.urlopen(url)
html_contents = str(html.read())
# print(html_contents)
id_results = re.findall(r"([A-Za-z0-9]+\*\*\*)", html_contents)
for result in id_results:
print(result)
import re
import urllib.request
url = "http://www.google.com/googlebooks/uspto-patents-grants-text.html"
html = urllib.request.urlopen(url)
html_contents = str(html.read().decode("utf8"))
url_list = re.findall(r"(http)(.+)(zip)", html_contents)
for url in url_list:
print("".join(url))
<dl class=”blind”> ~~~~</dl>
에 있는(\<dl class=\”blind\”\>)([\s\S]+?)(\<\/dl\>)
→ <dl class="blind">
에서 시작해서 / 사이에 아무 글자나 있고 / </dl>
로 끝내기<dd> ~~~~ </dd>
정보를 추출하면 됨(\<dd\>)([\s\S]+?)(\<\/dd\>)
→ <dd>
에서 시작해서 / 사이에 아무 글자나 있고 / </dd>
로 끝내기import re
import urllib.request
url = "http://finance.naver.com/item/main.nhn?code=005930"
html = urllib.request.urlopen(url)
html_contents = str(html.read().decode("ms949"))
stock_results = re.findall("(\<dl class=\"blind\"\>)([\s\S]+?)(\<\/dl\>)", html_contents)
samsung_stock = stock_results[0] # 두 tuple 값 중 첫 번째 패턴
samsung_index = samsung_stock[1] # 세 tuple 값 중 두 번째 값
index_list = re.findall("(\<dd\>)([\s\S]+?)(\<\/dd\>)", samsung_index)
print(index_list)
for index in index_list:
print(index[1])
<?xml version="1.0"?>
<고양이>
<이름>나비</이름>
<품종>샴</품종>
<나이>6</나이>
<중성화>예</중성화>
<발톱 제거>아니요</발톱 제거>
<등록 번호>Izz138bod</등록 번호>
<소유자>이강주</소유자>
</고양이>
<?xml version="1.0"?>
<books>
<book>
<author>Carson</author>
<price format="dollar">31.95</price>
<pubdate>05/01/2001</pubdate>
</book>
<pubinfo>
<publisher>MSPress</publisher>
<state>WA</state>
</pubinfo>
</books>
beautifulsoup
lxml
과 html5lib
과 같은 parser 사용<?xml version="1.0"?>
<books>
<book>
<author>Carson</author>
<price format="dollar">31.95</price>
<pubdate>05/01/2001</pubdate>
</book>
<pubinfo>
<publisher>MSPress</publisher>
<state>WA</state>
</pubinfo>
<book>
<author>Sungchul</author>
<price format="dollar">29.95</price>
<pubdate>05/01/2012</pubdate>
</book>
<pubinfo>
<publisher>Gachon</publisher>
<state>SeoungNam</state>
</pubinfo>
</books>
from bs4 import BeautifulSoup as bs
with open("books.xml", "r", encoding="utf8") as books_file:
books_xml = books_file.read() # file을 string으로 불러오기
# xml 모듈을 이용해 데이터 분석
soup = bs(books_xml, "lxml")
# author가 들어간 모든 element 추출
for book_info in soup.find_all("author"):
print(book_info)
print(book_info.get_text())
# invention-title에 대한 정보만 찾기
import urllib.request
from bs4 import BeautifulSoup as bs
with open("US08621662-20140107.xml", "r", encoding="utf8") as patent_xml:
xml = patent_xml.read() # file을 string으로 읽어오기
soup = bs(xml, "xml")
# print(soup)
# invention-title tag 찾기
invention_title_tag = soup.find("invention-title")
# print(invention_title_tag)
print(invention_title_tag.get_text())
# 출원번호, 출원일, 등록번호, 등록일, 상태, 특허명 추출
import urllib.request
from bs4 import BeautifulSoup as bs
with open("US08621662-20140107.xml", "r", encoding="utf8") as patent_xml:
xml = patent_xml.read() # file을 string으로 읽어오기
soup = bs(xml, "xml")
invention_title_tag = soup.find("invention-title")
# print(invention_title_tag)
publication_reference_tag = soup.find("publication-reference")
p_document_id_tag = publication_reference_tag.find("document-id")
p_country = p_document_id_tag.find("country").get_text()
p_doc_number = p_document_id_tag.find("doc-number").get_text()
p_kind = p_document_id_tag.find("kind").get_text()
p_date = p_document_id_tag.find("date").get_text()
print(publication_reference_tag)
print()
print(p_document_id_tag)
print()
print(p_doc_number, p_kind, p_date)
<?xml version=”1.0”
으로 시작등록번호
, 등록일자
, 출원 번호
, 출원 일자
, 상태
, 특허 제목
을 추출해 CSV 파일로 만들기<?xml version="1.0" encoding="UTF- 8" ?>
<employees>
<name>Shyam</name>
<email>shyamjaiswal@gmail.com</email>
</employees>
<employees>
<name>Bob</name>
<email>bob32@gmail.com</email>
</employees>
<employees>
<name>Jai</name>
<email>jai87@gmail.com</email>
</employees>
{
"employees":[
{"name":"Shyam",
"email":"shyamjaiswal@gmail.com"},
{"name":"Bob",
"email":"bob32@gmail.com"},
{"name":"Jai",
"email":"jai87@gmail.com"}
]
}
json
모듈을 사용해 쉽게 파싱 및 저장 가능import json
with open("json_example.json", "r", encoding="utf8") as f:
contents = f.read()
json_data = json.loads(contents)
print(json_data["employees"])
loads()
import json
dict_data = {"Name": "Zara", "Age": 7, "Class": "First"}
with open("data.json", "w") as f:
json.dump(dict_data, f)
dump()