Language/Python

두근두근 파이썬 CH9 연습문제

Return 2021. 6. 22. 19:48

1번.

a =0
filename = input("파일 이름을 입력하시오 :")  #파일 입력받는다.

infile = open(filename,"r") # 파일 읽기모드로 연다 .

for line in infile:
    line = line.strip() #글자 수 세기위해 공백 없앤다.
    b = len(line) #글자 갯수
    a = a+b

infile.close() #파일 닫늗다.

print("{}의 글자가 있습니다.".format(a))

2번.

filename = input("파일 이름을 입력하세요 : ")  #파일 입력
delete_word = input("삭제할 문자열을 입력하세요 : ") # 삭제할 문자열 입력

myfile = open(filename, "r") #읽기모드로 연다.
modified_s = ""

for line in myfile:
    line = line.rstrip() #오른쪽공백 없앤다.
    word_list = line.split() #공백 기준으로 문자열 나눈다. 
    if delete_word in word_list: #문자열 리스트에 삭제할 단어가 있다면 
        word_list.remove(delete_word) #리스트에서 삭제한다. 

    for word in word_list: #문자열 리스트에 있는 단어들을 수정된 텍스트에 다시 집어넣는다. 
        modified_s += word + " "


myfile.close()#파일 닫느다. 
myfile = open(filename, "w") #쓰기 모드로 연다.
myfile.write(modified_s) #수정된 텍스트 쓴다.
myfile.close()#파일 닫는다.

3번.

dic = {} #빈 딕셔너리 만든다. 

filename = input("파일 이름을 입력하시오:")  #파일 입력
infile = open(filename,"r")#파일 연다. 
x = infile.read()#파일을 읽는다. 

for line in x:       #파일에 있는 글자들 검사 
        if line in dic: #딕셔너리 안에 있으면 해당 value 값 증가 
            dic[line] +=1
        else: #딕셔너리안에 없으면 처음 넣으므로 1집어넣는다. 
            dic[line] = 1

print(dic)

infile.close()

4번.

import pickle

list_list = [] #빈리스트 만든다.

#a,b,c값 입력 받는다.
a = input("")
b = input("")
c = input("")

#각각 리스트에 집어넣는다.
list_list.append(a)
list_list.append(b)
list_list.append(c)

file = open("/Users/leejunseung/text.dat","wb")
pickle.dump(list_list,file) #데이터 입력 

file.close()

5번.

a = 0 #초기화 ,선언
b = 0

filename1 = input("입력 파일 이름: ") #파일 입력받는다.
filename2 = input("출력 파일 이름: ")

infile = open(filename1, "r") #읽기로 연다.
outfile = open(filename2, "w") #쓰리고 연다.
line = infile.readline() #각각의 줄 읽어들인다.

while line != "" :#각각의 줄에 대해
   k = float(line) #계산위해 float변수로 바꿔준다.
   a = a + k #총합
   b = b + 1 #갯수
   line = infile.readline() #다음줄

outfile.write("합계="+ str(a)+"\n") #합계

avg = a / b #평균
outfile.write("평균="+ str(avg)+"\n")

infile.close()
outfile.close()

6번.

from tkinter import *
import pickle

filename = "phone_book.dat" #파일 이름 지정
phone_book = {} #빈 딕셔너 만든다.
index = 0 #초기 선언

def add(): #추가 기능
    phone_book[e1.get()] = e2.get() #엔트리값 가져와 딕셔너리에 지정
    file = open(filename,"wb") #wb모드로 오픈
    pickle.dump(phone_book, file)# 입력
    file.close()

def fristindex():#처음 버튼
    global index
    index = 0
    phone_list = list(phone_book) #딕셔너리를 리스트로 바꾼다. 딕셔너리의 키 값들을 리스트 형태로 가짐
    e1.delete(0, "end")  #엔트리 초기화 
    e2.delete(0, "end") 
    e1.insert(0, phone_list[index]) #해당 문자열을 엔트리 위젯에 쓴다. 
    e2.insert(0, phone_book[phone_list[index]])#해당 키에 대한 밸류값을 엔트리에 쓴다. 

def Next(): #다음 버튼
    global index
    phone_list = list(phone_book)
    if(index == len(phone_list)-1):#index와 len 차이 보정된게 같다면
        index = 0
    else:
        index += 1
    e1.delete(0, "end") #엔트리 초기화 
    e2.delete(0, "end")
    e1.insert(0, phone_list[index]) #다음에 해당하는 문자열 엔트리에 쓴다. 
    e2.insert(0, phone_book[phone_list[index]])

def Before(): #이전 버튼
    global index
    phone_list = list(phone_book)
    if(index == 0):
        index = len(phone_list)-1 #index와 len 차이 보정
    else:
        index -= 1
    e1.delete(0, "end") #엔트리 초기화 
    e2.delete(0, "end")
    e1.insert(0, phone_list[index])#다음에 해당하는 문자열 엔트리에 쓴다. 
    e2.insert(0, phone_book[phone_list[index]])

def Last(): #마지막 버튼
    phone_list = list(phone_book)
    global index
    index = len(phone_list)-1 #index와 len 차이 보정
    e1.delete(0, "end")#엔트리 초기화 
    e2.delete(0, "end")
    e1.insert(0, phone_list[index])#다음에 해당하는 문자열 엔트리에 쓴다. 
    e2.insert(0, phone_book[phone_list[index]])

def read(): #읽기 버튼
    file = open(filename, "rb")
    obj = pickle.load(file)#데이터 로드
    print(obj)
    file.close()

window = Tk()

#각 라벨,엔트리, 버튼들 grid이용해 집어넣는다.

l1 = Label(window, text="이름"); l1.grid(row=0, column=0)
l2 = Label(window, text="전화번호"); l2.grid(row=1, column=0)

e1 = Entry(window); e1.grid(row=0, column=1, columnspan=5)
e2 = Entry(window); e2.grid( row=1, column=1, columnspan=5)

b1 = Button(window, text="추가", command=add); b1.grid(row=2, column=0)
b2 = Button(window, text="처음", command=fristindex); b2.grid(row=2, column=1)
b3 = Button(window, text="다음", command=Next); b3.grid(row=2, column=2)
b4 = Button(window, text="이전", command=Before); b4.grid(row=2, column=3)
b5 = Button(window, text="마지막", command=Last); b5.grid(row=2, column=4)
b6 = Button(window, text="파일 읽기", command=read); b6.grid(row=2, column=5)

window.mainloop()