Пример #1
0
# print(a_soup.find_all('span')[1].text)

span_list = a_soup.find_all('span')

'span 태그 텍스트 출력'
# for i in span_list:
#   print(i.text)
'''
4. 태그 안에 정의된 특정 클래스를 찾아 모으기
'''

quotes = a_soup.find_all('div', {'class': 'quote'})
# print("quote", quote)

quotes_list = []
for i in quotes:
    contents = i.text

    content = re.findall('.+', contents)
    quote = content[0]
    author = content[1][2:]
    tags = content[5:]

    print(quote, author, tags)

    quotes_list.append([quote, author, tags])

print(quotes_list)

usecsv.writecsv('the_quotes.csv', quotes_list)
Пример #2
0
# new = [['구', '한국인', '외국인', '외국인 비율(%)']]

# i = newPop[1]
# foreign = round(i[2] / (i[1] + i[2]) * 100, 1)

# new.append([i[0], i[1], i[2], foreign])

# print(new)

# for i in newPop:
#     foreign = 0
#     try:
#         foreign = round(i[2] / (i[1] + i[2]) * 100, 1)
#         if foreign > 3:
#             print([i[0], i[1], i[2], foreign])
#     except:
#         pass

new = [['구', '한국인', '외국인', '외국인 비율(%)']]

for i in newPop:
    foreign = 0
    try:
        foreign = round(i[2] / (i[1] + i[2]) * 100, 1)
        if foreign > 3:
            new.append([i[0], [1], i[2], foreign])
    except:
        pass

usecsv.writecsv('newPop.csv', new)
import usecsv
import numpy as np
import os
os.chdir(r'C:\Users\alstn\PycharmProjects\data-analysis-Pandas-Numpy\Numpy')
# quest.csv 저장한 경로

# 파일을 열어 숫자 원소를 실수형으로 바꾼 후 배열 형태로 저장
quest = np.array(usecsv.swith(usecsv.opencsv('quest.csv')))

print(quest)

# 4보다 큰 점수를 만점인 5점으로 동기화
quest[quest > 5] = 5
# 결과물을 저장
usecsv.writecsv('result.csv', list(quest))
Пример #4
0
import usecsv, os

os.chdir('./target')
a = [['국어', '영어', '수학'], [99, 88, 77]]
usecsv.writecsv('test.csv', a)
Пример #5
0
os.chdir(
    r'D:\VisualStudioCode\Python\Do_it_Python_Programming_in_Life\chapter04')
apt = usecsv.switch(usecsv.opencsv('apt_202109.csv'))

# print(apt[:3])
# print(len(apt))

# for i in apt[:6]:
#     print(i[0])

# for i in apt[:6]:
#     print(i[0], i[4], i[-4])

# for i in apt:
#     try:
#         if i[5] >= 120 and i[-4] <= 30000 and re.match('강원', i[0]):
#             print(i[0], i[4], i[-4])

#     except:
#         pass

new_list = []
for i in apt:
    try:
        if i[5] >= 120 and i[-4] <= 30000 and re.match('강원', i[0]):
            new_list.append([i[0], i[4], i[-4]])
    except:
        pass

usecsv.writecsv('over120_lower3000.csv', new_list)
Пример #6
0
import os
os.chdir(r'C:\Users\ERC\Documents\GitHub\PythonBasic\csv')
import usecsv
ad = [[1, 2, 3], ['우리', '나라', '만세'], ['나는', '우리나라가', '좋다']]
usecsv.writecsv('new_write_file.csv', ad)
total = usecsv.opencsv('new.csv')
print(total)
'''

# for i in officetel_info[:30]:
#   print(i[0], i[4], i[5], i[6], i[9], i[10])

'3. 궁금한 실거래 조건 검색해서 csv로 저장하기'

count = 0
the_officetel = []
print('내가 궁금한 실거래 조건')
print("오피스텔 헤더:", officetel_info[0])
the_officetel.append(officetel_info[0])

for i in officetel_info:

    try:

        if i[5] == '전세' and (i[6] >= 30 and i[6] <= 60) and re.search(
                '성남', i[0]):
            count += 1
            the_officetel.append(i)
            print("officetel_info:", i)
            # print("total count:", count)

    except:
        pass

print(count)

usecsv.writecsv('the_future_house.csv', the_officetel)
Пример #8
0
        if i[-4] > 150000:
            #출력조건: 지역, 단지명, 크기, 층수, 거래금액
            newlist.append([
                re.match('[가-힣]+ [가-힣]+', i[0]).group(), i[4], i[5], i[-3],
                i[-4]
            ])
    except:
        pass

print(newlist[0])
region = list(set([i[0] for i in newlist]))
summary = []
nameApt = list(set([i[1] for i in newlist]))
price = [i[-1] for i in newlist]

k = 0
# 각 지역에 해당 조건 아파트가 몇 채 있는지 summary
for j in region:
    for i in newlist:
        if i[0] == j:
            k += 1
    summary.append([j, k])
    k = 0

usecsv.writecsv('apt_over150,000.csv', newlist)
usecsv.writecsv('apt_sum_over150,000.csv', summary)

import numpy as np
price2 = np.array([price])
print(price2.mean(), price2.max())
Пример #9
0
    url = (
        'https://www.coupang.com/np/search?q=%EB%85%B8%ED%8A%B8%EB%B6%81&channel=user&component=&eventCategory=SRP&trcid=&traid=&sorter=scoreDesc&minPrice=&maxPrice=&priceRange=&filterType=&listSize=36&filter=&isPriceRange=false&brand=&offerCondition=&rating=0&page='
        + str(page) +
        '&rocketAll=false&searchIndexingToken=1=4&backgroundColor=')
    headers = {
        "User-Agent":
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36'
    }
    res = requests.get(url, headers=headers)
    soup = bs(res.text, 'lxml')
    for i in soup.find_all('li', {'class': 'search-product'}):
        name = i.find('div', {'class': 'name'}).text
        #print('https://www.coupang.com'+i.find('a').get('href') )
        try:
            new.append([
                name,
                i.find('strong', {
                    'class': 'price-value'
                }).text,
                i.find('span', {
                    'class': 'rating-total-count'
                }).text, 'https://www.coupang.com' + i.find('a').get('href')
            ])
        except:
            pass

import usecsv
new = usecsv.switch(new)
usecsv.writecsv('coupang(p)_suc.csv', new)
# 상품정보 담는 데까지 성공
Пример #10
0
# 크로바 아파트 들어가 아파트 정보 저장하는데 성공
import requests, re, time, usecsv
from bs4 import BeautifulSoup as bs
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(
    r'C:\Users\ERC\Documents\파이썬\패스트캠퍼스\자료\크롤링\selenium\chromedriver.exe')
driver.get('https://land.naver.com/')
apt = '크로바\n'
#크로바 아파트로 들어가는 데까지는 성공
driver.find_element_by_id('queryInputHeader').send_keys(apt)
title = driver.find_elements_by_class_name('title')
address = driver.find_elements_by_class_name('address')
#find_elements로 정보를 모아서 text로 출력하게 하는 것이 핵심
info = driver.find_elements_by_class_name('info_area')
crova_list = []
for i in range(len(title)):
    try:
        crova_list.append([title[i].text, address[i].text, info[i].text])
    except:
        pass
for i in crova_list:
    if i[0] != '':
        crova_list.append(i)
print(crova_list)
usecsv.writecsv('crova_csv(p).py', crova_list)
Пример #11
0
import re, usecsv, os

english = 'She is a vegetarian. She does not eat meat. She thinks that animals should not be killed. It is hard for her to hang out with people. Many people like to eat meat. She told his parents not to have meat. They laughed at her. She realized they couldn\'t give up meat.'

korean = '그녀는 채식주의자입니다. 그녀는 고기를 먹지 않습니다. 그녀는 동물을 죽이지 말아야한다고 생각합니다. 그녀가 사람들과 어울리는 것은 어렵습니다. 많은 사람들이 고기를 좋아합니다. 그녀는 부모에게 고기를 먹지 말라고 말했습니다. 그들은 그녀를 비웃었다. 그녀는 그들이 고기를 포기할 수 없다는 것을 깨달았습니다. '

os.chdir('./target')

korean_list = re.split('\.', korean)

english_list = re.split('\.', english)

print(korean_list)

total = []

for i in range(len(english_list)):

    total.append([english_list[i], korean_list[i]])

usecsv.writecsv('translation.csv', total)
Пример #12
0
import csv, usecsv, os
csv_test = [['국어', '영어', '수학'], [90, 80, 100]]
os.chdir(r'D:\user\Documents\git hub\PythonBasic\csv')
usecsv.writecsv('score.csv', csv_test)
Пример #13
0
'''
new_table.append([tot[0], tot[1], tot[2], f_ratio])
print(new_table)
'''



'4. 외국인 비율이 3% 넘을 때만 출력하기'

for lst in new_pop:
  ratio = 0

  try:
    ratio = (lst[2] / (lst[1] + lst[2])) * 100
    f_ratio = round(ratio, 2)

    if f_ratio > 5.0:
      new_table.append([lst[0], lst[1], lst[2], f_ratio])
    
    print("write",new_table)

  except:
    pass



'5. writecsv로 저장'

usecsv.writecsv('foreign_table.csv', new_table)
Пример #14
0
import usecsv, os

os.chdir('C:\Learning\Python\eleven_projects_python\\04_handling_csv\\test')
subjects = [['korean', 'english', 'math'], [34, 56, 44]]

usecsv.writecsv('test_return.csv', subjects)

Пример #15
0
# 크로바 아파트 들어가 아파트 이름, 주소, 정보까지 출력하는데 성공, csv화는 미성공
import requests, re, time, usecsv
from bs4 import BeautifulSoup as bs
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(r'C:\Users\ERC\Documents\파이썬\chromedriver.exe')
driver.get('https://land.naver.com/')
#정상적으로 작동하게 하여 아파트 이름만 대도 갈 수 있도록 해야
apt = '크로바\n'
#크로바 아파트로 들어가는 데까지는 성공
driver.find_element_by_id('queryInputHeader').send_keys(apt)
time.sleep(10)
title = driver.find_elements_by_class_name('title')
address = driver.find_elements_by_class_name('address')
#find_elements로 정보를 모아서 text로 출력하게 하는 것이 핵심
info = driver.find_elements_by_class_name('info_area')
crova_list = []
for i in range(len(title)):
    if title[i].text != '':
        try:
            crova_list.append([title[i].text, address[i].text, info[i].text])
        except:
            pass

usecsv.writecsv('crova_suc_sleep10.csv', crova_list)
Пример #16
0
import re, usecsv, os
# 사용할 모듈을 임포트

English = 'She is a vegetarian. She does not eat meat. She thinks that animals should not be killed. It is hard for her to hang out with people. Many people like to eat meat. She told his parents not to have meat. They laughed at her. She realized they couldn\'t give up meat.'
# 영문을 English 객체에 저장
Korean = '그녀는 채식주의자입니다. 그녀는 고기를 먹지 않습니다. 그녀는 동물을 죽이지 말아야한다고 생각합니다. 그녀가 사람들과 어울리는 것은 어렵습니다. 많은 사람들이 고기를 좋아합니다. 그녀는 부모에게 고기를 먹지 말라고 말했습니다. 그들은 그녀를 비웃었다. 그녀는 그들이 고기를 포기할 수 없다는 것을 깨달았습니다. '
# 영문을 구글 번역기로 번역해 Korean 객체에 저장

os.chdir(r'C:\Users\alstn\PycharmProjects\handling-data-with-csv-files')
# CSV 파일을 저장하고 싶은 폴더로 이동

Korean_list = re.split('\.', Korean)
# split() 함수로 한글 문장을 나눠서 Korean_list 에 저장
English_list = re.split('\.',English)
# 영문도 마침표를 기준으로 나눠서 English_list 에 저장
print(Korean_list)
# 중간 점검으로 Korean_list 를 출력

total = []
# csv 형 자료를 저장할 빈 리스트를 생성
for i in range(len(English_list)):
	# for 문을 English_list 객체에 들어 있는 문장 수만큼 반복
	total.append([English_list[i], Korean_list[i]]	)
# 첫 번째 열에 영어 문장, 두 번째 열에 한국어 문장이 들어 있는 리스트를 total 에 추가
usecsv.writecsv('Korean_English.csv', total)
Пример #17
0
        'https://www.coupang.com/np/search?q=%EB%85%B8%ED%8A%B8%EB%B6%81&channel=user&component=&eventCategory=SRP&trcid=&traid=&sorter=scoreDesc&minPrice=&maxPrice=&priceRange=&filterType=&listSize=36&filter=&isPriceRange=false&brand=&offerCondition=&rating=0&page='
        + str(page) +
        '&rocketAll=false&searchIndexingToken=1=4&backgroundColor=')
    headers = {
        "User-Agent":
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36'
    }
    res = requests.get(url, headers=headers)
    soup = bs(res.text, 'lxml')
    for i in soup.find_all('li', {'class': 'search-product'}):
        name = i.find('div', {'class': 'name'}).text
        # print('https:'+i.find('img', {'class':'search-product-wrap-img'}).get('data-img-src'))
        print('https://www.coupang.com' + i.find('a').get('href'))
        try:
            new.append([
                name,
                i.find('strong', {
                    'class': 'price-value'
                }).text,
                i.find('span', {
                    'class': 'rating-total-count'
                }).text, 'https://www.coupang.com' + i.find('a').get('href')
            ])
        except:
            pass
print(new)
import usecsv
#new = usecsv.switch(new)
usecsv.writecsv('coupang_newinfo.csv', new)
# 상품정보 담는 데까지 성공
Пример #18
0
import re, usecsv, os

english = 'She is a vegetarian. She does not eat meat. She thinks that animals should not be killed.'
korean = '그녀는 채식주의자 입니다. 그녀는 고기를 먹지않습니다. 그녀는 동물을 죽이지 말아야한다고 생각합니다.'

os.chdir(
    r'D:\VisualStudioCode\Python\Do_it_Python_Programming_in_Life\chapter04')

korean_list = re.split('\.', korean)
english_list = re.split('\.', english)

print(korean_list)

total = []

for i in range(len(english_list)):
    total.append([english_list[i], korean_list[i]])

usecsv.writecsv('korean_english.csv', total)