티스토리 뷰

#d:\\word.dat 파일 사용하며, 파일이 없을 때는 자동 생성되며,
#기본 정보까지 넣는다.
#관계 없는 d:\\word.dat가 있을 경우에는 지우고 실행해야 한다.

import random
import sys
import shelve
FPATH = "d:\\words.dat"

class confuse:
    
    
    __list = []

    def __init__(self):
        __switch_x = 0

        try:
            file = open(FPATH,"r")
        except IOError:
            print "First Start Game!!\n"
            __switch_x = 1
        else:
            file.close()


        try:
            self.__dic = shelve.open(FPATH)
            print "File --> Dic...\n"
        except IOError:
            print >> sys.stderr, "File could not be opened..."
            sys.exit(1)

        if(__switch_x == 1):
            __tempdic = {"sun":"태양","test":"연습, 실험",
                         "level":"단계","human":"사람",
                         "rock":"바위","love":"사랑",
                         "lover":"연인","classic":"오래된, 고전의",
                         "mouse":"쥐","stawberry":"딸기"
                }
            self.__dic.update(__tempdic)
        self.__list = self.__dic.keys()

    def printlist(self):
        return self.__list

    def insertword(self,word,detail):
        self.__dic[word] = detail
        
        self.__list = self.__dic.keys()

    def searchword(self,word):
        try:
            searchValue = self.__dic[word]
        except KeyError:
            return "NULL"
        else:
            return searchValue

    def chooseword(self):
        random.shuffle(self.__list)
        string = self.__list[0]
        strlist = []
        for x in string:
            strlist.append(x)
        random.shuffle(strlist)

        strshuffle = ""
        for x in strlist:
            strshuffle += x

        return [strshuffle,string,self.__dic[string]]

    def delword(self,word):
        del self.__dic[word]

        self.__list = self.__dic.keys()

game = confuse()
while 1:
    print "\n\n===== !Confuse! ====="
    print "SELECT ---> 1. START"
    print "            2. INSERT"
    print "            3. PRINT"
    print "            4. DELETE"
    print "            0. EXIT"
    print "====================="

    sel = raw_input(" >")
    print ""

    if(sel == "1"):
        exam = game.chooseword()
        print "===== EXAM =====".center(20)
        print exam[0].center(20)
        print "================".center(20)
        print exam[2].center(20)
        print "================".center(20)
        tt = raw_input("답 >")

        print ""
        if(tt == exam[1]):
            print "정답!!"
        else:
            print "오답!!"
    elif(sel == "2"):
        t1 = raw_input("영 단어 : ")
        t2 = raw_input("뜻 : ")

        if(game.searchword(t1) != "NULL"):
            print "입력된 단어입니다."
        else:
            print "단어를 입력합니다."
            game.insertword(t1,t2)
    elif(sel == "3"):
        print game.printlist()
    elif(sel == "4"):
        tt = raw_input("지울 단어 : ")

        if(game.searchword(tt) == "NULL"):
            print "지울 단어는 없습니다."
        else:
            print "단어를 지웁니다."
            game.delword(tt)
        
    elif(sel == "0"):
        print "게임을 끝냅니다."
        break;

밑의 영어 단어 맞추기 게임에서 File 과 연동되게 만들었다.

Python에서는 재미있게도, shelve 라는 모듈이 있는데, 이 녀석은 파일과 연동되어서 파일 자체를 사전형(해쉬)형태로 사용하게 만들어 준다.

그냥 shelve.open 만 해주면 파일에 저장, 로드를 자동으로 해주고, 프로그래머는 사전형을 사용하는 것 처럼 이용하면 끝.

위 소스는 최초 실행 할 때, 자료가 새로 만들어지면서 저장되게 만들었다.

파일의 유무를 판단하는 매소드를 저러한 형식으로 대체해 버렸다.
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함