본문 바로가기

웹_프론트_백엔드/Python

2020.02.04

1. lec02_file.py

# -*- coding: utf-8 -*-
#파일 입출력
#형식 : 변수 = open(파일이름, 모드, 문자저장방식)
#파일이름 :파일 path의 string. 
#모드: 
#w:write
#r:read
#a:append (파일의 끝에 추가)

#t:text
#b:binary

#문자저장방식 :utf-8이 디폴트 

#파일읽기 메서드 : read(), readline(), readlines()
#파일쓰기 메서드 : write(),            writelines()

text= '''
누구를 위해 누군가 기도하고 있나 봐
숨죽여 쓴 사랑시가 낮게 들리는 듯해
너에게로 선명히 날아가
늦지 않게 자리에 닿기를
I'll be there 홀로 걷는 너의 뒤에
Singing till the end 그치지 않을 이 노래
아주 잠시만 귀 기울여 봐
유난히 긴 밤을 걷는 널 위해 부를게
또 한 번 너의 세상에 별이 지고 있나 봐
숨죽여 삼킨 눈물이 여기 흐르는 듯해
할 말을 잃어 고요한 마음에
기억처럼 들려오는 목소리
I'll be there 홀로 걷는 너의 뒤에
Singing till the end 그치지 않을 이 노래
아주 커다란 숨을 쉬어…
'''

import os
#print(text)
#base_dir를 설정
base_dir = os.path.dirname(os.path.abspath(__file__))
print(base_dir)
file_path = os.path.join(base_dir, 'data_synopsis.txt')
file_copy_path = os.path.join(base_dir, 'data_synopsis_copy.txt')

##########1
#파일쓰기 :write()
f=open(file_path, 'wt', encoding='utf-8')
f.write(text)
f.close()
#파일읽기 :read()
f= open(file_path, 'rt', encoding='utf-8')
text2 = f.read()
f.close()
#print(text2)

##########2 리스트로 하는 방법
#파일읽기 : readlines()
f=open(file_path, 'rt', encoding='utf-8')
lines = f.readlines()
f.close()

#파일쓰기 :writelines()
f= open(file_copy_path, 'wt', encoding='utf-8')
f.writelines(lines)
f.close()

#lines를 화면에 출력하기 
for line in lines : 
    print(line,end='')

#######################2020.02.04 여기서부터 시작############################
#file open한후에 file을 반드시 close
#with를 사용하면 파일이 자동으로 close가 됨. 
#with, iterator사용한 방법
lines=[] 
with open(file_path, 'rt', encoding='utf-8' ) as f:
    for line in f:
        lines.append(line)
print(lines)

#with로 파일쓰기 
with open(file_copy_path, 'wt',  encoding='utf-8') as f:
    for line in lines:
        f.write(line)

#for문을 돌면서 lines[]의 데이터를 하나의 string으로 묶기 
text2=''
for line in lines:
    text2 +=line
print(text2)
     
#단어단위로 나누기(tokenizing)토큰으로 나누기 
words = text2.split()
print(words)
#단어의 출현횟수를 딕셔너리에 담기
word_count={}
# {'순간':5, '분야의':10}
for word in words:
    if word in word_count : 
        word_count[word] +=1
    else :
        word_count[word] = 1
print(word_count)

# key로 sorting하는법 
word_count_sort = sorted (word_count)        
print(word_count_sort)    #키만 sorting이 됨. 

for item in word_count.items() :
    print(item[0], item[1])
    
#value로 sortin하는 법 
word_count_sort =sorted(word_count.items(), key=lambda x:x[1], reverse =True )
#print(word_count_sort)    #키만 sorting이 됨. output은 리스트 

for item in word_count_sort[:10] :
    print(item)

2. data_user.csv

1001,Sean,100
1002,Lee,90
1003,Kim,95
1004,Michael,55
1005,Jenny,73

3. lec03_file_csv.py

# -*- coding: utf-8 -*-
# csv file입출력
# csv: comma seperated values  (쉼표로 필드가 분리된 파일. excel에서도 읽힘)

import csv
import os

base_dir = os.path.dirname(os.path.abspath(__file__))
print(base_dir)
file_path = os.path.join(base_dir, 'data_user.csv')
print(file_path)

#파일읽어서 출력 with, iterator로 읽기
lines=[]
with open(file_path, 'rt') as f:
    for line in f :
        lines.append(line)
print(lines)

#csv 모듈활용하기
with open(file_path, 'rt' ) as f:
    reader = csv.reader(f)
    lines2 = [line for line in reader]
print(lines2)
    
# key가 이름이고 value가 점수인 딕셔너리 만들기 
user = {}
for line in lines2[:]: #[:] :전체  [:3] 앞에 3개  
    #print(line)
    name = line[1]
    score = line[2]
    user[name] =score
    
print(user)
# 점수순으로 sorting
user_sorted = sorted(user.items(), key=lambda x:int(x[1]), reverse = True)
print(user_sorted)

# lambda는 익명함수이다. 잠깐 사용하기 위하여. 일회성
print(user.items())
def val(x) : 
    return int(x[1])
user_sorted = sorted(user.items(), key=val, reverse = True)
print(user_sorted)
keys = list(user.keys())
values = list(user.values())
values_int= list(map(lambda x:int(x), values))
import matplotlib.pyplot as plt 
plt.plot(keys, values_int, 'bo')

'웹_프론트_백엔드 > Python' 카테고리의 다른 글

2020.02.03  (0) 2020.02.04
2020.01.31  (0) 2020.02.03
2020.01.30  (0) 2020.01.30
2020.01.29  (0) 2020.01.29
2020.01.28  (0) 2020.01.28