본문 바로가기
Research/Python

Python_웹 스크래핑을 위한 기본 문법

by RIEM 2023. 3. 25.
# All the datas are same data type
states = ["California", "Texas", "Florida", "New York"]

# Indexing
# 파이썬은 0 based list
print(states[0]) # California

print(states[3]) # New York

print(states[-1]) # New York

print(states[-4]) #California


# For loop
for state in states:
    # If statement
    if state == "Florida":
        print(state);


# create file by writing
# open.. 블라블라를 file로 치환
# 실행하면 실제 txt 파일이 생성된다
with open('test.txt', 'w') as file:
    file.write("Data successfully scraped!")

인덱싱, 루프, 파일 저장 등 기본 문법이다.

 

import pandas as pd

# All the datas are same data type
states = ["California", "Texas", "Florida", "New York"]
population = [123124, 2412, 178457, 4124]

dict_states = {'States':states, 'Population': population}

# 데이터 프레임 생성
df_states = pd.DataFrame.from_dict(dict_states)
print(df_states)

#        States  Population
# 0  California      123124
# 1       Texas        2412
# 2     Florida      178457
# 3    New York        4124

# csv 파일로 저장
df_states.to_csv('states.csv', index=False)

딕셔너리를 데이터프레임으로 생성하여 csv 파일로 저장하기. 옵션 사용하여 인덱스 없이 저장하기.

 

# Python에서 예외 처리하는 방법
new_list = [2, 4, 5, 'California']

for element in new_list:
    try:
        print(element / 2)
    except:
        print("The element was not a number..")

"""
1.0
2.0
2.5
The element was not a number..
Process finished with exit code 0
"""

예외 처리하는 방법

# While-break
n = 4
while n < 10:
    print(n)
    n = n + 1
    if n == 5:
        break

print('We are done')

"""
4
We are done
"""

While 문

댓글