본문 바로가기

python

파이썬 기반의 채팅 프로그램(2024-03-08)

구현 목표

 

1. 기본적인 채팅 입출력(O)

2. 채팅 로그 저장 및 조회(TXT 파일 형태, 채팅 시간 및 사용자 저장까지가 최종 목표)(임시구현 상태)

3. 채팅 로그 초기화(O)

4. 특정 욕설 검열(EX: 메이플의 가세요라, 어머, 사이퍼즈의 하트 등)(아직 구현 못함)

5. 검열전 검열 후 비교 출력

import os


def get_chat_input():
    # 사용자로부터 채팅을 입력받아 반환
    chat_input = input("채팅창에 오신걸 환영합니다!\n종료하려면 'exit'를 입력하세요. : ")
    if chat_input.lower() == 'exit':
        return None
    return chat_input


def save_to_chat_log(chat_input, log_filename):
    # 입력한 채팅을 로그 파일에 저장
    with open(log_filename, "a") as log_file:
        log_file.write(chat_input + "\n")


def read_chat_log(log_filename):
    # 로그 파일을 열어서 내용을 출력
    if os.path.exists(log_filename):
        print("채팅 로그 내용:")
        with open(log_filename, "r") as log_file:
            chat_logs = log_file.readlines()
            for chat_log in chat_logs:
                print(chat_log, end='')
    else:
        print("채팅 로그 파일이 존재하지 않습니다.")



def clear_chat_log(log_filename):
    # 로그 파일 내용을 초기화하는 함수
    if os.path.exists(log_filename):
        with open(log_filename, "w") as log_file:
            log_file.write("")  # 빈 문자열로 파일 내용 초기화
        print(f"'{log_filename}' 파일의 내용이 초기화되었습니다.")
    else:
        print(f"'{log_filename}' 파일이 존재하지 않습니다.")

def replace_word_in_logs(log_filename, word, replacement):
    # 로그 파일을 읽어서 특정 단어를 다른 단어로 대체한 후 출력
    replaced_logs = ['씨발','좆', '개새끼']
    with open(log_filename, "r") as log_file:
        chat_logs = log_file.readlines()
        for chat_log in chat_logs:
            replaced_log = chat_log.replace(word, replacement)
            replaced_logs.append(replaced_log)

    for replaced_log in replaced_logs:
        print(replaced_log, end='')


def main():
    # 로그를 저장할 파일 이름
    log_filename = "chat_log.txt"

    # 채팅 입력과 로그 파일 처리
    while True:
        chat_input = get_chat_input()
        if chat_input is None:
            break
        save_to_chat_log(chat_input, log_filename)

    # 프로그램을 종료하기 직전 'exit'를 입력한 경우에만 로그 파일을 처리할지 여부를 묻습니다.
    if input("로그 파일을 초기화하시겠습니까? (y/n): ").lower() == "y":
        clear_chat_log(log_filename)
        response = input("로그 파일을 읽으시겠습니까? (y/n): ").lower()
        if response == "y":
            read_chat_log(log_filename)
        elif response == "n":
            response = input("특정 단어를 대체한 로그를 출력하시겠습니까? (y/n): ").lower()
            if response == "y":
                word = input("대체할 특정 단어를 입력하세요: ")
                replacement = ("어머")
                replace_word_in_logs(log_filename, word, replacement)


if __name__ == "__main__":
    main()