Python
08장 GUI와 파일 처리
renne
2022. 6. 12. 22:13
목차
8.1 GUI
8.2 파일 처리
8.3 파일 처리 응용
8.4 모듈
8.1 GUI
GUI
- Graphic User Interface
easygui 모듈
buttonbox(" ", choices = []) | 버튼 박스 |
choicebox(" ", choices = []) | 여러 항목 선택 박스 |
msgbox(" ") | 메시지 출력 박스 |
enterbox(" ") | 문자열을 입력받음 |
integerbox(" ") | 정수를 입력받음 |
import easygui, random
answer = random.randint(1, 10)
times = int(easygui.buttonbox("도전 기회 선택", choices = ['3', '4']))
num = 0
while num != answer and times > 0:
num = easygui.integerbox("1 ~ 10 사이의 숫자를 입력하시오.")
if num < answer:
easygui.msgbox(str(num) + "은/는 정답보다 작다.")
elif num > answer:
easygui.msgbox(str(num) + "은/는 정답보다 크다.")
times -= 1
if num == answer:
easygui.msgbox("정답")
else:
easygui.msgbox("더 이상 기회가 없다. 정답은 " + str(answer))
randint 모듈
import random
answer = random.randint(1, 100) #1 ~ 100 사이의 난수
8.2 파일 처리
텍스트 파일 읽기
파일변수 = open('파일이름') | 동일한 폴더에 있으면 '파일이름.txt' 다른 폴더에 있으면 '파일경로포함.txt' |
파일변수.readline() | 한 행을 일고 그 내용을 문자열로 반환 파일에 남아있는 행이 없을 경우 ' ' 반환 |
파일변수.close() |
f = open('memo.txt')
mymemo = []
while True:
line = f.readline()
if len(line) == 0:
break
line = line.strip() #앞뒤의 스페이스 제거
mymemo.append(line)
f.close()
print(mymemo)
<memo.txt>
mon
tue
wed
thu
fri
<실행 결과>
['mon', 'tue', 'wed', 'thu', 'fri']
텍스트 파일 쓰기
mymemo = []
while True:
item = input("item to buy: ")
if len(item) == 0:
break
mymemo.append(item)
f = open('memo.txt', 'w') #텍스트 파일을 쓰기 모드로 열기
for item in mymemo:
f.write(item + '\n') #write 메서드로 파일에 내용 작성
f.close()
<실행 결과>
item to buy: apple
item to buy: book
item to buy: pencil
item to buy:
<memo.txt>
apple
book
pencil
8.3 파일 처리 응용
텍스트 파일 내의 단어 빈도 계산
Unlike Pluto - Everything Black
f = open('black.txt')
counts = {}
for line in f:
list = line.split() #space를 기준으로 단어 구분
for word in list:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
f.close()
for word in sorted(counts):
print(word, counts[word])
<실행 결과>
And 3
Baby, 6
Black 15
Black, 15
Blackout, 3
But 2
Children 1
Dancing 1
Do 2
Hit 3
I 3
I'll 2
I've 1
In 1
Keys, 3
Me 3
Of 1
Shadows 1
Should 6
This 1
Underneath 1
With 3
You 4
a 7
and 6
around 1
bad 2
bird, 3
black 22
black, 4
blackout 4
blackout, 6
can 3
closed 1
come 7
dancing 1
dark 4
diamonds 3
everything 18
everything, 12
eyes 1
fall 1
for 1
got 1
heart 4
heart, 1
hit 3
hole's 1
in 4
inside 1
it's 1
kill 3
life 1
light 3
lights 6
lights, 3
me 11
mind 1
moon 4
my 2
night 3
nocturnal 1
of 3
only 1
out, 3
over 1
pulling 1
side 2
sky 1
sky, 3
sleep 1
soul 1
state 1
take 2
the 19
things 2
this 2
time 2
to 3
tonight 1
wait 1
way 1
we 3
with 9
won't 1
woo 3
you 12
f = open('black.txt')
counts = {}
for line in f:
list = line.lower().split() #대문자를 소문자로
for word in list:
word = word.strip(".,") #단어 앞뒤의 온점과 반점 제거
counts[word] = counts.get(word, 0) +1
f.close()
for word in sorted(counts):
print(word, counts[word])
<실행 결과>
a 7
and 9
around 1
baby 6
bad 2
bird 3
black 56
blackout 13
but 2
can 3
children 1
closed 1
come 7
dancing 2
dark 4
diamonds 3
do 2
everything 30
eyes 1
fall 1
for 1
got 1
heart 5
hit 6
hole's 1
i 3
i'll 2
i've 1
in 5
inside 1
it's 1
keys 3
kill 3
life 1
light 3
lights 9
me 14
mind 1
moon 4
my 2
night 3
nocturnal 1
of 4
only 1
out 3
over 1
pulling 1
shadows 1
should 6
side 2
sky 4
sleep 1
soul 1
state 1
take 2
the 19
things 2
this 3
time 2
to 3
tonight 1
underneath 1
wait 1
way 1
we 3
with 12
won't 1
woo 3
you 16
dictionary.get(x, n)
if x in dic:
return dic[x]
else:
return n
8.4 모듈
- 함수, 변수 또는 클래스를 모아놓은 파이썬 파일
- import하여 사용할 수 있다.
- 이미 만들어진 것을 사용하거나, 직접 만들어서 사용할 수 있다.
#모듈을 import
import random
print(random.randint(1, 100)) #모듈이름.함수이름
#모듈에서 함수를 import
from random import randint
print(randint(1, 100)) #함수이름만
#모듈에서 모든 함수를 import
from random import *