21.12.01 파이썬 파일 다루기 / 데이터 구조 다루기 / 그래프 다루기

2021. 12. 1. 15:44작업/데이터분석

파일 다루기

# 1.
file = open('data.txt')
content = file.read()
file.close()
# 2.
with open('data.txt') as file:
	content = file.read() # file.close()가 필요없다.
    
# 3. 파일의 모드
with open('data.txt', 'w') as file: # 읽기 모드
	file.write('Hello')

한 줄씩 읽어와서 배열에 담기

contents = []
with open('data.txt') as file:
	for line in file:
    	content.append(line)
# 텍스트 파일을 불러옵니다.
filename = 'corpus.txt'

def print_lines(filename):
    # 아래 코드를 작성하세요.
        line_number = 1    
            # 1 This is Elice. 와 같이, "(줄번호) (내용)" 형식으로 출력합니다.
        with open(filename) as file:
            for i in file:
                print(f'{line_number} {i}')
                line_number += 1


# 아래 주석을 해제하고 결과를 확인해보세요.  
print_lines(filename)

파이썬의 데이터 구조

튜플과 리스트

fruits = ['apple','cherry','strawberry'] # 배열
fruits = ('apple','cherry','strawberry') # 튜플

- 둘다 순서기 있는 원소들의 집합 fruits[0] 가능

- 튜플은 각 원소의 값을 수정할 수 없고, 원소의 개수를 바꿀 수 없음. 리스트는 그 반대

fruits[0]='banana' / fruits.append('pear')

- 단 튜플 변경하려면 아예 새로운 튜플을 넣어주는 것은 가능

fruits = ('kiwi','pear','banana') # 튜플
# 텍스트 파일을 불러옵니다.
filename = 'corpus.txt'

def import_as_tuple(filename):
    tuples = []
    with open(filename) as file:
        for line in file:
            # 아래 코드를 작성하세요.
            split = line.strip().split(',') # strip -> line으로 읽어올 때 자동으로 읽어오는 앞뒤에 있는 \n 공백문자들을 없애줌
            word = split[0]
            freq = split[1]
            new_tuple=(word,freq)
            tuples.append(new_tuple)
    return tuples


# 아래 주석을 해제하고 결과를 확인해보세요.  
print(import_as_tuple(filename))
fruits = ['apple','cherry','strawberry']

# 1.
new_list = [fruit[0] for fruit in fruits]

# 2.
new_list = [fruit[0] for fruit in fruits if fruit[0]=='a']
words = [
    'apple',
    'banana',
    'alpha',
    'bravo',
    'cherry',
    'charlie',
]

def filter_by_prefix(words, prefix):
    # 아래 코드를 작성하세요.
    new_list = [word for word in words if word[0]==prefix]
    return new_list


# 아래 주석을 해제하고 결과를 확인해보세요.  
a_words = filter_by_prefix(words, 'a')
print(a_words)

데이터 정렬하기 sorted, sort()

# 1.
nums = [-1,3,-4,5,-6]
sort_by_abs = sorted(nums, key=abs) # 두 번째(key) 인자에 아무것도 없으면 오름차순
# 두 번째(key)인자에 어떤 함수에 들어가 있으면 그 함수의 결과에 따라 정렬


# 2. 
fruits = ['cherry','apple','banana']
sort_by_alphabet = sorted(fruits)

# 3.
def reverse(word):
	return str(reversed(word)) # 'elppa'
    
fruits = ['cherry','apple','banana']
sort_by_alphabet = sorted(fruits, key=reverse)

sort : 원본 값을 바꿈, 리턴 값이 없음

sorted : 원본 값은 유지, 리턴 값이 있음

 

diamonds = sorted(diamonds, key=lambda x:-x['price'] # 원본값 유지, 리턴 값 있음.

diamonds.sort() # 원본값 변경, 리턴 없음

 

# 해당 단어의 빈도수를 담은 리스트를 선언합니다. 수정하지 마세요.
pairs = [
    ('time', 8),
    ('the', 15),
    ('turbo', 1),
]



#(단어, 빈도수) 쌍으로 이루어진 튜플을 받아, 빈도수를 리턴합니다.    
def get_freq(pair):
    return pair[1]



#(단어, 빈도수) 꼴 튜플의 리스트를 받아, 빈도수가 낮은 순서대로 정렬하여 리턴합니다.
def sort_by_frequency(pairs):
    sorted_pairs = sorted(pairs, key=get_freq)
    return sorted_pairs


# 아래 주석을 해제하고 결과를 확인해보세요.  
print(sort_by_frequency(pairs))

 

그래프 다루기 matplotlib (파이썬에서 그래프 그려주는 라이브러리)

# matplotlib의 일부인 pyplot 라이브러리를 불러옵니다.
import matplotlib.pyplot as plt

# 월별 평균 기온을 선언합니다. 수정하지 마세요.
years = [2013, 2014, 2015, 2016, 2017]
temperatures = [5, 10, 15, 20, 17]

#막대 차트를 출력합니다.   
def draw_graph():
    # 막대 그래프의 막대 위치를 결정하는 pos를 선언합니다.
    pos = range(len(years))  # [0, 1, 2, 3, 4]
    
    # 높이가 온도인 막대 그래프를 그립니다.
    # 각 막대를 가운데 정렬합니다.
    plt.bar(pos, temperatures, align='center')
    
    # 각 막대에 해당되는 연도를 표기합니다.
    plt.xticks(pos, years)
    
    # 그래프를 엘리스 플랫폼 상에 표시합니다.
    plt.savefig('graph.png')
    elice_utils.send_image('graph.png')

print('막대 차트를 출력합니다.')
draw_graph()

'작업 > 데이터분석' 카테고리의 다른 글

21.12.06 파이썬 데이터처리 모의테스트  (0) 2021.12.06
21.12.06 파이썬 정리2  (0) 2021.12.06
21.12.06 파이썬 정리 1  (0) 2021.12.06
21.12.04 numpy, pandas  (0) 2021.12.05
21.12.02 JSON, CSV  (0) 2021.12.04