Data Analysis

MBTI 테스트 프로그램

곽수진 2021. 9. 2. 22:55
반응형

전체 코드

import random

questionsList = []

class Question:
    def __init__(self, question, group):
        self.question = question[0]
        self.direction = question[1]
        self.group = group
        self.A = True
        self.B = False
        self.scores = None

    def ask(self):
        """
        uses a while loop to ask user a question
        their answer determines the score which is returned

        returns answer value
        """
        while True:
            print(self.question)
            answer = input("yes or no: ")
            print()
            if answer.lower() == "yes" or answer.lower() == "no":
                answer = answer.lower()
                if answer == "yes":
                    answer = True
                    break
                else:
                    answer = False
                    break
            else:
                print("not a valid answer")
                continue
        if self.direction:
            if answer:  # answer was yes
                self.scores = questionScores(self.A, self.group)
                return None
            else:
                self.scores = questionScores(self.B, self.group)
                return None

        else:  # question answer is reversed
            if answer:
                self.scores = questionScores(self.B, self.group)
                return None
            else:
                self.scores = questionScores(self.A, self.group)
                return None

    def getQuestion(self):
        return self.question

    def getDirection(self):
        return self.direction

    def getScores(self):
        return self.scores

opennessItems = [["i have excellent ideas", True],
                 ["i am quick to understand things", True],
                 ["i use difficult words", True],
                 ["i am full of ideas", True],
                 ["i am not interested in abstractions", False],
                 ["i do not have a good imagination", False],
                 ["i have difficulty understanding abstract ideas", False]
                 ]

conscientiousnessItems = [["i am always prepared", True],
                          ["i pay attention to detail", True],
                          ["i get chores done right away", True],
                          ["i like order", True],
                          ["i follow a schedule", True],
                          ["i am exacting in my work", True],
                          ["i leave my belongings around", False],
                          ["i make a mess of things", False],
                          ["i often forget to put things back in their proper place", False],
                          ["i shirk my duties", False]
                          ]

extroversionItems = [["i am the life of the party", True],
                     ["i don't mind being the center of attention", True],
                     ["i feel comfortable around people", True],
                     ["i start conversations", True],
                     ["i talk to a lot of different people at parties", True],
                     ["i don't talk a lot", False],
                     ["i think a lot before i speak or act", False],
                     ["i don't like to draw attention to myself", False],
                     ["i am quiet around strangers", False],
                     ["i have no intention of talking in large crowds", False]
                     ]

agreeablenessItems = [["i am interested in people", True],
                      ["i sympathize with others' feelings", True],
                      ["i have a soft heart", True],
                      ["i take time out for others", True],
                      ["i feel others' emotions", True],
                      ["i make people feel at ease", True],
                      ["i am not really interested in others", False],
                      ["i insult people", False],
                      ["i am not interested in other people's problems", False],
                      ["i feel little concern for others", False]
                      ]

neuroticismItems = [["i get irritated easily", True],
                    ["i get stressed out easily", True],
                    ["i get upset easily", True],
                    ["i have frequent mood swings", True],
                    ["i worry about things", True],
                    ["i am much more anxious than most people", True],
                    ["i am relaxed most of the time", False],
                    ["i seldom feel blue", False]
                    ]

def createQuestions():

    print()
    print("loading...")
    print()

    print("creating openness questions...")
    for statement in opennessItems:
        question = Question(statement, "O")
        questionsList.append(question)

    print("creating conscientiousness questions...")
    for statement in conscientiousnessItems:
        question = Question(statement, "C")
        questionsList.append(question)

    print("creating extroversion questions...")
    for statement in extroversionItems:
        question = Question(statement, "E")
        questionsList.append(question)

    print("creating agreeableness questions...")
    for statement in agreeablenessItems:
        question = Question(statement, "A")
        questionsList.append(question)

    print("creating neuroticism questions...")
    for statement in neuroticismItems:
        question = Question(statement, "N")
        questionsList.append(question)

    print()
    print()
    print("Welcome to my personality test!")
    print()

    return None


def questionScores(answer, group):
    scores = []
    if answer:
        if group == "N":
            scores.append(-0.18)  # E
            scores.append(0.14)  # I
            scores.append(-0.16)  # S
            scores.append(0.21)  # N
            scores.append(-0.29)  # T
            scores.append(0.36)  # F
            scores.append(-0.25)  # J
            scores.append(0.30)  # P
            return scores

        elif group == "E":
            scores.append(0.58)  # E
            scores.append(-0.58)  # I
            scores.append(-0.08)  # S
            scores.append(0.02)  # N
            scores.append(0.02)  # T
            scores.append(0.05)  # F
            scores.append(-0.06)  # J
            scores.append(0.03)  # P
            return scores

        elif group == "O":
            scores.append(-0.30)  # E
            scores.append(0.30)  # I
            scores.append(-0.60)  # S
            scores.append(0.71)  # N
            scores.append(-0.34)  # T
            scores.append(0.35)  # F
            scores.append(-0.07)  # J
            scores.append(0.03)  # P
            return scores

        elif group == "A":
            scores.append(-0.08)  # E
            scores.append(-0.01)  # I
            scores.append(-0.11)  # S
            scores.append(0.29)  # N
            scores.append(0.52)  # T
            scores.append(0.52)  # F
            scores.append(0.00)  # J
            scores.append(0.00)  # P
            return scores

        elif group == "C":
            scores.append(-0.11)  # E
            scores.append(0.01)  # I
            scores.append(0.03)  # S
            scores.append(0.03)  # N
            scores.append(0.02)  # T
            scores.append(0.02)  # F
            scores.append(0.56)  # J
            scores.append(0.62)  # P
            return scores

        else:
            return None

    else:
        if group == "N":
            scores.append(-0.24)  # E
            scores.append(0.26)  # I
            scores.append(-0.02)  # S
            scores.append(0.03)  # N
            scores.append(-0.16)  # T
            scores.append(0.18)  # F
            scores.append(0.01)  # J
            scores.append(0.00)  # P
            return scores

        elif group == "E":
            scores.append(-0.69)  # E
            scores.append(0.46)  # I
            scores.append(-0.18)  # S
            scores.append(0.16)  # N
            scores.append(0.09)  # T
            scores.append(0.05)  # F
            scores.append(-0.03)  # J
            scores.append(0.02)  # P
            return scores

        elif group == "O":
            scores.append(0.21)  # E
            scores.append(0.22)  # I
            scores.append(0.52)  # S
            scores.append(0.49)  # N
            scores.append(0.22)  # T
            scores.append(0.22)  # F
            scores.append(-0.24)  # J
            scores.append(0.24)  # P
            return scores

        elif group == "A":
            scores.append(0.12)  # E
            scores.append(-0.01)  # I
            scores.append(0.03)  # S
            scores.append(0.03)  # N
            scores.append(0.40)  # T
            scores.append(0.40)  # F
            scores.append(0.06)  # J
            scores.append(0.00)  # P
            return scores

        elif group == "C":
            scores.append(0.03)  # E
            scores.append(0.06)  # I
            scores.append(0.20)  # S
            scores.append(0.24)  # N
            scores.append(-0.28)  # T
            scores.append(-0.28)  # F
            scores.append(0.50)  # J
            scores.append(-0.41)  # P
            return scores

        else:
            return None

def applyScores():
    global extroversion
    extroversion = 0
    global introversion
    introversion = 0
    global sensation
    sensation = 0
    global intuition
    intuition = 0
    global thinking
    thinking = 0
    global feeling
    feeling = 0
    global judging
    judging = 0
    global perceiving
    perceiving = 0

    for question in questionsList:
        scores = question.getScores()
        extroversion += scores[0]
        introversion += scores[1]
        sensation += scores[2]
        intuition += scores[3]
        thinking += scores[4]
        feeling += scores[5]
        judging += scores[6]
        perceiving += scores[7]
    return None

def askQuestions():
    for question in questionsList:
        question.ask()

    return None

def shareScore():
    score = ""
    print()
    print("loading...")
    if extroversion >= introversion:
        score += "E"
    else:
        score += "I"

    if sensation >= intuition:
        score += "S"
    else:
        score += "N"

    if thinking >= feeling:
        score += "T"
    else:
        score += "F"

    if judging >= perceiving:
        score += "J"
    else:
        score += "P"

    print()
    print("your type is: ", score)
    print()

    print("individual results: ")
    print("extroversion: ", str(extroversion))
    print("introversion: ", str(introversion))
    print("sensation: ", str(sensation))
    print("intuition: ", str(intuition))
    print("thinking: ", str(thinking))
    print("feeling: ", str(feeling))
    print("judging: ", str(judging))
    print("perceiving: ", str(perceiving))

    print()
    print()
    print("thank you for taking this test")
    print()
    print("inspired by the official Myers Briggs personality test")


def main():
    createQuestions()
    askQuestions()
    applyScores()
    shareScore()
    return None

main()

▶️ self, question, group을 매개변수로 갖는 __init__ 사용자 정의 함수 생성

questionsList = [] : MBTI를 확인하기 위한 질문을 저장할 questionList 리스트를 만듦

→ question 리스트에 저장된 0번, 1번 index의 값self.question, self.direction 변수에 저장

self.groupgroup을 의미

self.ATrue값을, self.BFalse값을 의미

class Question:
    def __init__(self, question, group):
        self.question = question[0]
        self.direction = question[1]
        self.group = group
        self.A = True
        self.B = False
        self.scores = None

 

▶️ self값을 매개변수로 갖는 ask 사용자 정의 함수를 생성

→ self.question에 저장된 질문을 출력해 사용자가 'yes' 혹은 'no'를 입력하도록 함

→ 사용자가 yes(소문자)를 입력했을 경우 answer에 True, no(소문자)를 입력했을 경우에 False를 저장함

'yes'나 'no'가 아닌 다른 값을 입력하면 유효한 정답이 아님을 출력함

self.direction의 경우, group에 정답이 yes면 true값, no면 false값을 저장하고 반대의 경우, yes면 false, no면 true값을 저장

def ask(self):
    while True:
        print(self.question)
        answer = input("yes or no: ")
        print()
        if answer.lower() == "yes" or answer.lower() == "no":
            answer = answer.lower()
            if answer == "yes":
                answer = True
                break
            else:
                answer = False
                break
        else:
            print("not a valid answer")
            continue
    if self.direction:
        if answer:  # answer was yes
            self.scores = questionScores(self.A, self.group)
            return None
        else:
            self.scores = questionScores(self.B, self.group)
            return None

    else:  # question answer is reversed
        if answer:
            self.scores = questionScores(self.B, self.group)
            return None
        else:
            self.scores = questionScores(self.A, self.group)
            return None

 

▶️ 각각 self를 매개변수로 하는 getQuestion, getDirection, getScores 사용자 정의 함수를 생성함

→ 각각 self.question, self.direction, self.scores 값을 리턴

def getQuestion(self):
    return self.question

def getDirection(self):
    return self.direction

def getScores(self):
    return self.scores

 

▶️ 각각의 성향에 맞는 유형별 질문을 생성 후, true값이 나오면 점수가 높아지고, false값이 나오면 점수가 낮아짐

opennessItems = [["i have excellent ideas", True],
                 ["i am quick to understand things", True],
                 ["i use difficult words", True],
                 ["i am full of ideas", True],
                 ["i am not interested in abstractions", False],
                 ["i do not have a good imagination", False],
                 ["i have difficulty understanding abstract ideas", False]
                 ]

conscientiousnessItems = [["i am always prepared", True],
                          ["i pay attention to detail", True],
                          ["i get chores done right away", True],
                          ["i like order", True],
                          ["i follow a schedule", True],
                          ["i am exacting in my work", True],
                          ["i leave my belongings around", False],
                          ["i make a mess of things", False],
                          ["i often forget to put things back in their proper place", False],
                          ["i shirk my duties", False]
                          ]

extroversionItems = [["i am the life of the party", True],
                     ["i don't mind being the center of attention", True],
                     ["i feel comfortable around people", True],
                     ["i start conversations", True],
                     ["i talk to a lot of different people at parties", True],
                     ["i don't talk a lot", False],
                     ["i think a lot before i speak or act", False],
                     ["i don't like to draw attention to myself", False],
                     ["i am quiet around strangers", False],
                     ["i have no intention of talking in large crowds", False]
                     ]

agreeablenessItems = [["i am interested in people", True],
                      ["i sympathize with others' feelings", True],
                      ["i have a soft heart", True],
                      ["i take time out for others", True],
                      ["i feel others' emotions", True],
                      ["i make people feel at ease", True],
                      ["i am not really interested in others", False],
                      ["i insult people", False],
                      ["i am not interested in other people's problems", False],
                      ["i feel little concern for others", False]
                      ]

neuroticismItems = [["i get irritated easily", True],
                    ["i get stressed out easily", True],
                    ["i get upset easily", True],
                    ["i have frequent mood swings", True],
                    ["i worry about things", True],
                    ["i am much more anxious than most people", True],
                    ["i am relaxed most of the time", False],
                    ["i seldom feel blue", False]
                    ]

 

 

▶️ def createQuestions() : 사용자에게 물어볼 질문을 생성하는 함수

→ statement가 각각 해당하는 유형(opennessItems, conscientiousnessItems, extroversionItems, agreeablenessItems, neuroticismItems)에 존재한다면 questionList에 앞 글자(O, C, E, A, N)을 따서 저장됨

def createQuestions():

    print()
    print("loading...")
    print()

    print("creating openness questions...")
    for statement in opennessItems:
        question = Question(statement, "O")
        questionsList.append(question)

    print("creating conscientiousness questions...")
    for statement in conscientiousnessItems:
        question = Question(statement, "C")
        questionsList.append(question)

    print("creating extroversion questions...")
    for statement in extroversionItems:
        question = Question(statement, "E")
        questionsList.append(question)

    print("creating agreeableness questions...")
    for statement in agreeablenessItems:
        question = Question(statement, "A")
        questionsList.append(question)

    print("creating neuroticism questions...")
    for statement in neuroticismItems:
        question = Question(statement, "N")
        questionsList.append(question)

    print()
    print()
    print("Welcome to my personality test!")
    print()

    return None

 

▶️ def questionScores() : 사용자에게 물어봤던 질문들에서 ask() 함수로부터 얻었던 value값들을 근거로 한 answer 리스트 값

→ True, False 값에 대해 점수를 저장하는 함수

def questionScores(answer, group):
    # scores goes in E, I, S, N, T, F, J, P
    scores = []
    if answer:
        if group == "N":
            scores.append(-0.18)  # E
            scores.append(0.14)  # I
            scores.append(-0.16)  # S
            scores.append(0.21)  # N
            scores.append(-0.29)  # T
            scores.append(0.36)  # F
            scores.append(-0.25)  # J
            scores.append(0.30)  # P
            return scores

        elif group == "E":
            scores.append(0.58)  # E
            scores.append(-0.58)  # I
            scores.append(-0.08)  # S
            scores.append(0.02)  # N
            scores.append(0.02)  # T
            scores.append(0.05)  # F
            scores.append(-0.06)  # J
            scores.append(0.03)  # P
            return scores

        elif group == "O":
            scores.append(-0.30)  # E
            scores.append(0.30)  # I
            scores.append(-0.60)  # S
            scores.append(0.71)  # N
            scores.append(-0.34)  # T
            scores.append(0.35)  # F
            scores.append(-0.07)  # J
            scores.append(0.03)  # P
            return scores

        elif group == "A":
            scores.append(-0.08)  # E
            scores.append(-0.01)  # I
            scores.append(-0.11)  # S
            scores.append(0.29)  # N
            scores.append(0.52)  # T
            scores.append(0.52)  # F
            scores.append(0.00)  # J
            scores.append(0.00)  # P
            return scores

        elif group == "C":
            scores.append(-0.11)  # E
            scores.append(0.01)  # I
            scores.append(0.03)  # S
            scores.append(0.03)  # N
            scores.append(0.02)  # T
            scores.append(0.02)  # F
            scores.append(0.56)  # J
            scores.append(0.62)  # P
            return scores

        else:
            return None

    else:
        if group == "N":
            scores.append(-0.24)  # E
            scores.append(0.26)  # I
            scores.append(-0.02)  # S
            scores.append(0.03)  # N
            scores.append(-0.16)  # T
            scores.append(0.18)  # F
            scores.append(0.01)  # J
            scores.append(0.00)  # P
            return scores

        elif group == "E":
            scores.append(-0.69)  # E
            scores.append(0.46)  # I
            scores.append(-0.18)  # S
            scores.append(0.16)  # N
            scores.append(0.09)  # T
            scores.append(0.05)  # F
            scores.append(-0.03)  # J
            scores.append(0.02)  # P
            return scores

        elif group == "O":
            scores.append(0.21)  # E
            scores.append(0.22)  # I
            scores.append(0.52)  # S
            scores.append(0.49)  # N
            scores.append(0.22)  # T
            scores.append(0.22)  # F
            scores.append(-0.24)  # J
            scores.append(0.24)  # P
            return scores

        elif group == "A":
            scores.append(0.12)  # E
            scores.append(-0.01)  # I
            scores.append(0.03)  # S
            scores.append(0.03)  # N
            scores.append(0.40)  # T
            scores.append(0.40)  # F
            scores.append(0.06)  # J
            scores.append(0.00)  # P
            return scores

        elif group == "C":
            scores.append(0.03)  # E
            scores.append(0.06)  # I
            scores.append(0.20)  # S
            scores.append(0.24)  # N
            scores.append(-0.28)  # T
            scores.append(-0.28)  # F
            scores.append(0.50)  # J
            scores.append(-0.41)  # P
            return scores

        else:
            return None

 

▶️ def applyScores() : 분류하기 위해 모든 점수들을 더하기 위해 사용하는 함수

def applyScores():
    global extroversion
    extroversion = 0
    global introversion
    introversion = 0
    global sensation
    sensation = 0
    global intuition
    intuition = 0
    global thinking
    thinking = 0
    global feeling
    feeling = 0
    global judging
    judging = 0
    global perceiving
    perceiving = 0

    for question in questionsList:
        scores = question.getScores()
        extroversion += scores[0]
        introversion += scores[1]
        sensation += scores[2]
        intuition += scores[3]
        thinking += scores[4]
        feeling += scores[5]
        judging += scores[6]
        perceiving += scores[7]
    return None

 

▶️ def askQuestions() : 한 번에 모든 질문들을 출력하는 함수

def askQuestions():
    for question in questionsList:
        question.ask()

    return None

 

▶️ def shareScore() : 사용자에게 테스트 결과를 보여주기 위한 함수

def shareScore():
    score = ""
    print()
    print("loading...")
    if extroversion >= introversion:
        score += "E"
    else:
        score += "I"

    if sensation >= intuition:
        score += "S"
    else:
        score += "N"

    if thinking >= feeling:
        score += "T"
    else:
        score += "F"

    if judging >= perceiving:
        score += "J"
    else:
        score += "P"

    print()
    print("your type is: ", score)
    print()

    print("individual results: ")
    print("extroversion: ", str(extroversion))
    print("introversion: ", str(introversion))
    print("sensation: ", str(sensation))
    print("intuition: ", str(intuition))
    print("thinking: ", str(thinking))
    print("feeling: ", str(feeling))
    print("judging: ", str(judging))
    print("perceiving: ", str(perceiving))

 

 

▶️ conda activate begin_env(사용자명) : anaconda 활성화 시키기

▶️ cd C:\Users\9500DA-XC58B\Desktop\mypython\Day\7\examples : 위 코드가 작성된 파이썬 파일이 들어있는 폴더로 주소 변경하기

▶️ 위 코드가 작성된 파이썬 파일 실행

python mbti_test.py 실행시킴

 

 

결과값 출력 모습

▶️ 중간 생략한 MBTI test 실행 모습

반응형

'Data Analysis' 카테고리의 다른 글

[ Python ] 위치 문자  (0) 2021.09.09
영화 리뷰 분석  (0) 2021.09.09
Word Cloud 프로그램  (0) 2021.09.02
파이차트 그리기  (0) 2021.09.02
MBTI 데이터 분석 프로그램  (0) 2021.09.02