반응형
파이썬 문자열이란?
문자열(String)은 프로그래밍에서 가장 기본적이면서도 중요한 데이터 타입 중 하나입니다. 간단히 말해서 문자들이 연속적으로 나열된 것을 의미합니다. 예를 들어 "안녕하세요", "Python Programming", "12345" 같은 것들이 모두 문자열입니다.
파이썬에서 문자열을 만드는 방법은 총 네 가지가 있습니다. 이렇게 다양한 방법을 제공하는 이유는 각각의 상황에 맞게 사용할 수 있도록 하기 위함입니다.
문자열을 만드는 네 가지 방법
1. 큰따옴표 사용하기
python
# 기본적인 큰따옴표 사용법
message = "안녕하세요, 파이썬 세계에 오신 것을 환영합니다!"
print(message)
2. 작은따옴표 사용하기
python
# 작은따옴표로 문자열 만들기
greeting = '파이썬은 정말 재미있는 언어입니다'
print(greeting)
3. 큰따옴표 세 개 연속 사용하기
python
# 여러 줄 문자열을 위한 큰따옴표 세 개
long_text = """
파이썬은 간단하면서도 강력한 프로그래밍 언어입니다.
배우기 쉽고 사용하기 편리합니다.
데이터 분석, 웹 개발, 인공지능 등 다양한 분야에서 사용됩니다.
"""
print(long_text)
4. 작은따옴표 세 개 연속 사용하기
python
# 작은따옴표 세 개로 여러 줄 문자열 만들기
poem = '''
장미는 빨갛고
제비꽃은 파랗다
파이썬은 멋지고
프로그래밍은 즐겁다
'''
print(poem)
특수 상황에서의 문자열 처리
문자열 안에 따옴표 포함하기
실제 프로그래밍을 하다 보면 문자열 안에 따옴표를 포함해야 하는 경우가 자주 발생합니다.
1. 문자열에 작은따옴표 포함하기
python
# 올바른 방법: 큰따옴표로 감싸기
restaurant_review = "김씨의 맛집은 정말 훌륭한 곳입니다"
print(restaurant_review)
# 잘못된 방법 (오류 발생)
# wrong_text = '김씨의 맛집은 정말 좋아요' # SyntaxError 발생!
2. 문자열에 큰따옴표 포함하기
python
# 올바른 방법: 작은따옴표로 감싸기
famous_quote = '"성공은 1%의 영감과 99%의 노력으로 이루어진다" 라고 에디슨이 말했습니다'
print(famous_quote)
3. 역슬래시(백슬래시) 사용하기
python
# 역슬래시를 사용하여 특수문자 처리
movie_title = '영화 "어벤져스"는 정말 재미있어요'
book_title = "책 '해리포터'를 읽어보세요"
print(movie_title)
print(book_title)
이스케이프 문자 완전 정복
이스케이프 문자는 특별한 의미를 가진 문자 조합입니다. 역슬래시()와 특정 문자를 조합하여 만듭니다.
이스케이프 코드설명예제\n | 새로운 줄로 이동 | "첫 번째 줄\n두 번째 줄" |
\t | 탭 공간 추가 | "이름:\t홍길동" |
\ | 역슬래시 표시 | "파일 경로: C:\Users\Documents" |
' | 작은따옴표 표시 | '이것은 '특별한' 문자열입니다' |
" | 큰따옴표 표시 | "그는 "안녕하세요"라고 말했습니다" |
python
# 다양한 이스케이프 문자 사용 예제
def demonstrate_escape_characters():
"""이스케이프 문자들의 사용법을 보여주는 함수"""
# 줄바꿈 사용
print("첫 번째 줄입니다\n두 번째 줄입니다\n세 번째 줄입니다")
# 탭 사용으로 정렬하기
print("이름:\t홍길동")
print("나이:\t25세")
print("직업:\t프로그래머")
# 따옴표 포함하기
print("선생님이 \"열심히 공부하세요\"라고 말씀하셨습니다")
print('학생은 \'네, 알겠습니다\'라고 대답했습니다')
# 역슬래시 표시하기
print("윈도우 경로: C:\\Program Files\\Python")
# 함수 실행
demonstrate_escape_characters()
문자열 연산의 마법
파이썬의 가장 매력적인 특징 중 하나는 직관적인 문자열 연산입니다.
문자열 더하기 (연결하기)
python
# 기본적인 문자열 연결
first_name = "김"
last_name = "철수"
full_name = first_name + last_name
print("전체 이름:", full_name)
# 여러 문자열 연결하기
greeting = "안녕하세요, "
name = "파이썬 학습자"
ending = "님!"
complete_message = greeting + name + ending
print(complete_message)
# 숫자와 문자열 연결 (형 변환 필요)
age = 25
message = "저는 " + str(age) + "살입니다"
print(message)
문자열 곱하기 (반복하기)
python
# 기본적인 문자열 반복
laugh = "하하"
big_laugh = laugh * 5
print(big_laugh) # 하하하하하하하하하하
# 장식용 선 만들기
separator = "=" * 40
print(separator)
print("중요한 공지사항")
print(separator)
# 패턴 만들기
pattern = "♦♦♦ " * 8
print(pattern)
실용적인 문자열 연산 예제
python
def create_receipt():
"""영수증 형태의 출력을 만드는 함수"""
# 상점 정보
store_name = "파이썬 마트"
address = "서울시 강남구 파이썬로 123"
# 장식용 선
line = "=" * 50
thin_line = "-" * 50
# 영수증 헤더 출력
print(line)
print(" " * 20 + store_name)
print(" " * 15 + address)
print(line)
# 상품 목록
items = [
("파이썬 책", 25000),
("노트북", 1200000),
("마우스", 35000),
("키보드", 89000)
]
print("상품명" + " " * 20 + "가격")
print(thin_line)
total = 0
for item_name, price in items:
# 상품명과 가격을 적절히 정렬하여 출력
spacing = " " * (25 - len(item_name))
print(item_name + spacing + str(price) + "원")
total += price
print(thin_line)
print("합계:" + " " * 20 + str(total) + "원")
print(line)
# 영수증 생성
create_receipt()
문자열 길이 측정하기
len() 함수는 문자열의 길이를 측정하는 내장 함수입니다.
python
# 기본적인 길이 측정
message = "파이썬 프로그래밍은 재미있습니다"
length = len(message)
print(f"메시지의 길이: {length}자")
# 공백도 문자로 카운트됩니다
text_with_spaces = "Hello World Python"
print(f"공백 포함 길이: {len(text_with_spaces)}")
# 빈 문자열의 길이
empty_string = ""
print(f"빈 문자열의 길이: {len(empty_string)}")
# 실용적인 예제: 비밀번호 길이 검증
def validate_password(password):
"""비밀번호 길이를 검증하는 함수"""
min_length = 8
max_length = 20
current_length = len(password)
if current_length < min_length:
return f"비밀번호가 너무 짧습니다. (현재: {current_length}자, 최소: {min_length}자)"
elif current_length > max_length:
return f"비밀번호가 너무 깁니다. (현재: {current_length}자, 최대: {max_length}자)"
else:
return f"적절한 길이의 비밀번호입니다. ({current_length}자)"
# 비밀번호 검증 테스트
test_passwords = ["123", "mypassword123", "verylongpasswordthatexceedslimit"]
for pwd in test_passwords:
print(validate_password(pwd))
문자열 인덱싱: 문자 하나하나 접근하기
문자열의 각 문자는 번호(인덱스)를 가지고 있습니다. 파이썬에서는 0부터 시작합니다.
기본 인덱싱
python
# 문자열 인덱싱 기본
sentence = "Python Programming"
print("문자열:", sentence)
print()
# 각 위치의 문자 출력
print("첫 번째 문자 (인덱스 0):", sentence[0]) # P
print("두 번째 문자 (인덱스 1):", sentence[1]) # y
print("세 번째 문자 (인덱스 2):", sentence[2]) # t
print("일곱 번째 문자 (인덱스 6):", sentence[6]) # 공백
# 음수 인덱싱 (뒤에서부터)
print("마지막 문자:", sentence[-1]) # g
print("뒤에서 두 번째:", sentence[-2]) # n
print("뒤에서 세 번째:", sentence[-3]) # i
실용적인 인덱싱 예제
python
def analyze_string(text):
"""문자열을 분석하는 함수"""
print(f"='=' * 40")
print(f"문자열 분석: '{text}'")
print(f"='=' * 40")
# 기본 정보
print(f"길이: {len(text)}자")
if len(text) > 0:
print(f"첫 글자: '{text[0]}'")
print(f"마지막 글자: '{text[-1]}'")
# 중간 글자 찾기
middle_index = len(text) // 2
print(f"중간 글자 (인덱스 {middle_index}): '{text[middle_index]}'")
# 각 문자의 위치 출력
print("\n각 문자의 위치:")
for i in range(len(text)):
print(f"인덱스 {i:2d}: '{text[i]}'")
# 문자열 분석 실행
analyze_string("Hello")
analyze_string("파이썬")
문자열 슬라이싱: 부분 문자열 추출하기
슬라이싱은 문자열의 일부분을 잘라내는 기능입니다. [시작:끝:간격] 형태로 사용합니다.
기본 슬라이싱
python
# 슬라이싱 기본 사용법
text = "Python Programming Language"
print("원본 문자열:", text)
print()
# 기본 슬라이싱
print("처음부터 6번째까지:", text[0:6]) # Python
print("7번째부터 18번째까지:", text[7:18]) # Programming
print("19번째부터 끝까지:", text[19:]) # Language
# 시작 인덱스 생략
print("처음부터 6번째까지:", text[:6]) # Python
# 끝 인덱스 생략
print("7번째부터 끝까지:", text[7:]) # Programming Language
# 음수 인덱스 사용
print("뒤에서 8글자:", text[-8:]) # Language
print("뒤에서 8번째부터 뒤에서 1번째까지:", text[-8:-1]) # Languag
슬라이싱 간격 사용하기
python
# 간격을 사용한 슬라이싱
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
print("전체 알파벳:", alphabet)
# 2글자씩 건너뛰기
print("2글자씩:", alphabet[::2]) # ACEGIKMOQSUWY
# 3글자씩 건너뛰기
print("3글자씩:", alphabet[::3]) # ADGJMPSVY
# 역순으로 출력
print("거꾸로:", alphabet[::-1]) # ZYXWVUTSRQPONMLKJIHGFEDCBA
# 특정 구간을 역순으로
print("5-10구간 역순:", alphabet[5:10][::-1]) # JIHGF
고급 문자열 활용 팁
문자열 포맷팅
python
# f-string 사용법 (Python 3.6+)
name = "홍길동"
age = 25
height = 175.5
# 기본 포맷팅
intro = f"안녕하세요, 제 이름은 {name}입니다. 나이는 {age}세이고, 키는 {height}cm입니다."
print(intro)
# 소수점 제어
pi = 3.14159265359
print(f"원주율: {pi:.2f}") # 소수점 2자리까지
print(f"원주율: {pi:.4f}") # 소수점 4자리까지
# 문자열 정렬
print(f"{'왼쪽정렬':<10}|")
print(f"{'가운데정렬':^10}|")
print(f"{'오른쪽정렬':>10}|")
문자열 메서드 활용
python
def string_methods_demo():
"""유용한 문자열 메서드들을 시연하는 함수"""
sample_text = " Python Programming is Fun! "
print(f"원본: '{sample_text}'")
# 공백 제거
print(f"양쪽 공백 제거: '{sample_text.strip()}'")
print(f"왼쪽 공백 제거: '{sample_text.lstrip()}'")
print(f"오른쪽 공백 제거: '{sample_text.rstrip()}'")
# 대소문자 변환
clean_text = sample_text.strip()
print(f"모두 대문자: '{clean_text.upper()}'")
print(f"모두 소문자: '{clean_text.lower()}'")
print(f"첫 글자만 대문자: '{clean_text.capitalize()}'")
print(f"각 단어 첫 글자 대문자: '{clean_text.title()}'")
# 문자열 검색
print(f"'Python' 포함 여부: {clean_text.find('Python') != -1}")
print(f"'Java' 포함 여부: {clean_text.find('Java') != -1}")
# 문자열 분리와 결합
words = clean_text.split()
print(f"단어 분리: {words}")
rejoined = " | ".join(words)
print(f"다시 결합: '{rejoined}'")
string_methods_demo()
실전 프로젝트: 간단한 텍스트 에디터
python
def simple_text_editor():
"""간단한 텍스트 에디터 시뮬레이션"""
print("=" * 50)
print("간단한 텍스트 에디터")
print("=" * 50)
print("명령어:")
print("1. write - 텍스트 입력")
print("2. show - 현재 텍스트 보기")
print("3. length - 텍스트 길이 확인")
print("4. reverse - 텍스트 뒤집기")
print("5. upper - 대문자로 변환")
print("6. lower - 소문자로 변환")
print("7. clear - 텍스트 지우기")
print("8. quit - 프로그램 종료")
print("=" * 50)
text_content = ""
while True:
command = input("\n명령어를 입력하세요: ").strip().lower()
if command == "write":
new_text = input("입력할 텍스트: ")
text_content += new_text
print("✅ 텍스트가 추가되었습니다.")
elif command == "show":
print(f"현재 텍스트: '{text_content}'")
elif command == "length":
print(f"텍스트 길이: {len(text_content)}자")
elif command == "reverse":
reversed_text = text_content[::-1]
print(f"뒤집힌 텍스트: '{reversed_text}'")
elif command == "upper":
upper_text = text_content.upper()
print(f"대문자 변환: '{upper_text}'")
elif command == "lower":
lower_text = text_content.lower()
print(f"소문자 변환: '{lower_text}'")
elif command == "clear":
text_content = ""
print("✅ 텍스트가 지워졌습니다.")
elif command == "quit":
print
python
elif command == "quit":
print("👋 텍스트 에디터를 종료합니다.")
break
else:
print("❌ 잘못된 명령어입니다. 다시 입력해주세요.")
# 텍스트 에디터 실행
# simple_text_editor()
문자열 검증과 처리 함수들
python
def advanced_string_functions():
"""고급 문자열 처리 함수들"""
def validate_email(email):
"""간단한 이메일 형식 검증"""
if "@" in email and "." in email:
parts = email.split("@")
if len(parts) == 2 and len(parts[0]) > 0 and len(parts[1]) > 0:
domain = parts[1]
if "." in domain and len(domain.split(".")[-1]) >= 2:
return True
return False
def format_phone_number(phone):
"""전화번호 형식 정리"""
# 숫자만 추출
digits = ""
for char in phone:
if char.isdigit():
digits += char
# 11자리인 경우 포맷팅
if len(digits) == 11:
return f"{digits[:3]}-{digits[3:7]}-{digits[7:]}"
elif len(digits) == 10:
return f"{digits[:3]}-{digits[3:6]}-{digits[6:]}"
else:
return "잘못된 전화번호 형식"
def extract_numbers(text):
"""문자열에서 숫자만 추출"""
numbers = ""
for char in text:
if char.isdigit():
numbers += char
return numbers
def count_characters(text):
"""문자 유형별 개수 세기"""
result = {
'letters': 0, # 문자
'digits': 0, # 숫자
'spaces': 0, # 공백
'special': 0 # 특수문자
}
for char in text:
if char.isalpha():
result['letters'] += 1
elif char.isdigit():
result['digits'] += 1
elif char.isspace():
result['spaces'] += 1
else:
result['special'] += 1
return result
# 테스트 실행
print("📧 이메일 검증 테스트:")
test_emails = [
"user@example.com",
"invalid.email",
"test@domain.co.kr",
"@invalid.com",
"user@.com"
]
for email in test_emails:
is_valid = validate_email(email)
status = "✅ 유효" if is_valid else "❌ 무효"
print(f" {email:<20} - {status}")
print("\n📞 전화번호 포맷팅 테스트:")
test_phones = [
"01012345678",
"010-1234-5678",
"010 1234 5678",
"02-123-4567",
"031.123.4567"
]
for phone in test_phones:
formatted = format_phone_number(phone)
print(f" {phone:<15} → {formatted}")
print("\n🔢 숫자 추출 테스트:")
test_texts = [
"가격은 15,000원입니다",
"전화: 010-1234-5678",
"우편번호: 12345",
"abc123def456ghi"
]
for text in test_texts:
numbers = extract_numbers(text)
print(f" '{text}' → '{numbers}'")
print("\n📊 문자 분석 테스트:")
analysis_text = "Hello World 123! 안녕하세요 456?"
char_count = count_characters(analysis_text)
print(f" 분석 대상: '{analysis_text}'")
print(f" 문자: {char_count['letters']}개")
print(f" 숫자: {char_count['digits']}개")
print(f" 공백: {char_count['spaces']}개")
print(f" 특수문자: {char_count['special']}개")
# 고급 함수 실행
advanced_string_functions()
문자열 암호화와 복호화 게임
python
def cipher_game():
"""간단한 시저 암호화 게임"""
def caesar_cipher(text, shift, decrypt=False):
"""시저 암호화/복호화 함수"""
if decrypt:
shift = -shift
result = ""
for char in text:
if char.isalpha():
# 대문자와 소문자 구분
if char.isupper():
# A=65, Z=90
shifted = ((ord(char) - ord('A') + shift) % 26) + ord('A')
else:
# a=97, z=122
shifted = ((ord(char) - ord('a') + shift) % 26) + ord('a')
result += chr(shifted)
else:
# 알파벳이 아닌 문자는 그대로
result += char
return result
print("🔐 시저 암호화 게임")
print("=" * 40)
print("간단한 암호화를 체험해보세요!")
while True:
print("\n선택하세요:")
print("1. 암호화하기")
print("2. 복호화하기")
print("3. 암호 맞추기 게임")
print("4. 종료")
choice = input("선택 (1-4): ").strip()
if choice == "1":
text = input("암호화할 텍스트: ")
shift = int(input("이동할 칸 수 (1-25): "))
encrypted = caesar_cipher(text, shift)
print(f"암호화 결과: {encrypted}")
elif choice == "2":
text = input("복호화할 텍스트: ")
shift = int(input("이동했던 칸 수 (1-25): "))
decrypted = caesar_cipher(text, shift, decrypt=True)
print(f"복호화 결과: {decrypted}")
elif choice == "3":
# 게임 모드
original_messages = [
"HELLO PYTHON",
"PROGRAMMING IS FUN",
"LEARN TO CODE",
"STRING MANIPULATION"
]
import random
message = random.choice(original_messages)
shift = random.randint(1, 25)
encrypted = caesar_cipher(message, shift)
print(f"암호화된 메시지: {encrypted}")
print("원본 메시지를 맞춰보세요!")
attempts = 3
while attempts > 0:
guess = input(f"추측 ({attempts}번 기회 남음): ").upper()
if guess == message:
print("🎉 정답입니다!")
break
else:
attempts -= 1
if attempts > 0:
print("❌ 틀렸습니다. 다시 시도하세요.")
else:
print(f"❌ 실패! 정답은 '{message}'였습니다.")
elif choice == "4":
print("👋 게임을 종료합니다.")
break
else:
print("❌ 잘못된 선택입니다.")
# 암호화 게임 실행
# cipher_game()
문자열 패턴 매칭과 정규표현식 기초
python
def pattern_matching_basics():
"""문자열 패턴 매칭 기초"""
def find_pattern(text, pattern):
"""간단한 패턴 찾기 함수"""
positions = []
start = 0
while True:
pos = text.find(pattern, start)
if pos == -1:
break
positions.append(pos)
start = pos + 1
return positions
def replace_pattern(text, old_pattern, new_pattern):
"""패턴 바꾸기 함수"""
return text.replace(old_pattern, new_pattern)
def extract_words(text):
"""단어 추출하기"""
words = []
current_word = ""
for char in text:
if char.isalpha():
current_word += char
else:
if current_word:
words.append(current_word)
current_word = ""
# 마지막 단어 처리
if current_word:
words.append(current_word)
return words
def validate_korean_name(name):
"""한글 이름 형식 검증"""
if len(name) < 2 or len(name) > 4:
return False
for char in name:
# 한글 유니코드 범위: 가(44032) ~ 힣(55203)
if not (44032 <= ord(char) <= 55203):
return False
return True
# 테스트 실행
print("🔍 패턴 찾기 테스트:")
test_text = "Python is powerful. Python is easy. Python is fun."
pattern = "Python"
positions = find_pattern(test_text, pattern)
print(f" 텍스트: '{test_text}'")
print(f" 패턴 '{pattern}' 위치: {positions}")
print("\n🔄 패턴 바꾸기 테스트:")
replaced = replace_pattern(test_text, "Python", "프로그래밍")
print(f" 바뀐 결과: '{replaced}'")
print("\n📝 단어 추출 테스트:")
sample_text = "Hello, World! This is a test."
words = extract_words(sample_text)
print(f" 원본: '{sample_text}'")
print(f" 추출된 단어: {words}")
print("\n🇰🇷 한글 이름 검증 테스트:")
test_names = ["김철수", "이영희", "박", "정수진아", "John", "김영수"]
for name in test_names:
is_valid = validate_korean_name(name)
status = "✅ 유효" if is_valid else "❌ 무효"
print(f" '{name}' - {status}")
# 패턴 매칭 테스트 실행
pattern_matching_basics()
문자열 성능 최적화 팁
python
def string_performance_tips():
"""문자열 성능 최적화 방법들"""
import time
def test_string_concatenation():
"""문자열 연결 성능 비교"""
print("⚡ 문자열 연결 성능 비교:")
# 방법 1: + 연산자 사용 (비효율적)
start_time = time.time()
result1 = ""
for i in range(1000):
result1 += str(i) + " "
time1 = time.time() - start_time
# 방법 2: join 사용 (효율적)
start_time = time.time()
parts = []
for i in range(1000):
parts.append(str(i))
result2 = " ".join(parts)
time2 = time.time() - start_time
# 방법 3: f-string 사용
start_time = time.time()
parts = []
for i in range(1000):
parts.append(f"{i}")
result3 = " ".join(parts)
time3 = time.time() - start_time
print(f" + 연산자: {time1:.4f}초")
print(f" join 사용: {time2:.4f}초")
print(f" f-string + join: {time3:.4f}초")
print(f" join이 + 연산자보다 {time1/time2:.1f}배 빠름")
def memory_efficient_string_processing():
"""메모리 효율적인 문자열 처리"""
print("\n💾 메모리 효율적인 문자열 처리:")
# 큰 텍스트 처리 시뮬레이션
large_text = "파이썬 프로그래밍을 배우는 것은 정말 즐거운 일입니다. " * 100
# 비효율적인 방법: 전체 텍스트를 메모리에 로드
def inefficient_word_count(text):
words = text.split()
return len(words)
# 효율적인 방법: 청크 단위로 처리
def efficient_word_count(text, chunk_size=100):
word_count = 0
for i in range(0, len(text), chunk_size):
chunk = text[i:i+chunk_size]
# 단어 경계 처리
if i + chunk_size < len(text) and not text[i+chunk_size].isspace():
last_space = chunk.rfind(' ')
if last_space != -1:
chunk = chunk[:last_space]
word_count += len(chunk.split())
return word_count
count1 = inefficient_word_count(large_text)
count2 = efficient_word_count(large_text)
print(f" 일반적인 방법: {count1}개 단어")
print(f" 청크 처리 방법: {count2}개 단어")
# 성능 테스트 실행
test_string_concatenation()
memory_efficient_string_processing()
# 성능 최적화 테스트 실행
string_performance_tips()
종합 실습 프로젝트: 텍스트 분석기
python
def comprehensive_text_analyzer():
"""종합적인 텍스트 분석기"""
def analyze_comprehensive(text):
"""텍스트 종합 분석"""
results = {}
# 기본 통계
results['총_문자수'] = len(text)
results['공백_제외_문자수'] = len(text.replace(' ', ''))
results['단어수'] = len(text.split())
results['문장수'] = text.count('.') + text.count('!') + text.count('?')
# 문자 유형별 분석
char_analysis = {
'영문자': 0, '한글': 0, '숫자': 0,
'공백': 0, '특수문자': 0
}
for char in text:
if char.isalpha():
if ord(char) < 128: # ASCII 범위 (영문)
char_analysis['영문자'] += 1
else: # 한글 또는 기타
char_analysis['한글'] += 1
elif char.isdigit():
char_analysis['숫자'] += 1
elif char.isspace():
char_analysis['공백'] += 1
else:
char_analysis['특수문자'] += 1
results['문자_분석'] = char_analysis
# 단어 빈도 분석
words = text.lower().split()
word_freq = {}
for word in words:
# 특수문자 제거
clean_word = ""
for char in word:
if char.isalnum():
clean_word += char
if clean_word:
word_freq[clean_word] = word_freq.get(clean_word, 0) + 1
# 상위 5개 단어
sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)
results['빈도수_높은_단어'] = sorted_words[:5]
# 가독성 분석 (간단한 지표)
avg_word_length = sum(len(word) for word in words) / len(words) if words else 0
results['평균_단어_길이'] = round(avg_word_length, 2)
if results['문장수'] > 0:
avg_sentence_length = results['단어수'] / results['문장수']
results['평균_문장_길이'] = round(avg_sentence_length, 2)
else:
results['평균_문장_길이'] = 0
return results
def display_analysis(results):
"""분석 결과를 보기 좋게 출력"""
print("📊 텍스트 분석 결과")
print("=" * 50)
print("📈 기본 통계:")
print(f" 전체 문자 수: {results['총_문자수']:,}자")
print(f" 공백 제외: {results['공백_제외_문자수']:,}자")
print(f" 단어 수: {results['단어수']:,}개")
print(f" 문장 수: {results['문장수']:,}개")
print("\n🔤 문자 구성:")
for char_type, count in results['문자_분석'].items():
percentage = (count / results['총_문자수'] * 100) if results['총_문자수'] > 0 else 0
print(f" {char_type}: {count:,}개 ({percentage:.1f}%)")
print("\n🏆 빈도수가 높은 단어:")
for i, (word, freq) in enumerate(results['빈도수_높은_단어'], 1):
print(f" {i}. '{word}': {freq}번")
print("\n📏 가독성 지표:")
print(f" 평균 단어 길이: {results['평균_단어_길이']}자")
print(f" 평균 문장 길이: {results['평균_문장_길이']}단어")
# 가독성 평가
if results['평균_단어_길이'] < 4:
readability = "쉬움"
elif results['평균_단어_길이'] < 6:
readability = "보통"
else:
readability = "어려움"
print(f" 예상 난이도: {readability}")
# 샘플 텍스트들
sample_texts = {
"소설": """
어느 날 갑자기 세상이 변했다. 하늘은 붉게 물들었고,
사람들은 모두 집 안에 숨어버렸다. 주인공은 이 상황을
이해할 수 없었다. 그는 용기를 내어 밖으로 나가기로
결심했다. 거리는 조용했고, 바람만이 쓸쓸히 불고 있었다.
""",
"기술문서": """
Python is a high-level programming language. It was created by
Guido van Rossum and first released in 1991. Python's design
philosophy emphasizes code readability with its notable use of
significant whitespace. The language provides constructs intended
to enable writing clear programs on both small and large scales.
""",
"뉴스": """
오늘 정부는 새로운 경제정책을 발표했습니다. 이 정책은
중소기업 지원과 일자리 창출에 초점을 맞추고 있습니다.
전문가들은 이번 정책이 경제 회복에 도움이 될 것으로
전망한다고 밝혔습니다. 시행은 다음 달부터 시작됩니다.
"""
}
print("🎯 텍스트 분석기에 오신 것을 환영합니다!")
print("=" * 50)
while True:
print("\n선택하세요:")
print("1. 샘플 텍스트 분석")
print("2. 직접 입력한 텍스트 분석")
print("3. 파일에서 텍스트 읽어서 분석")
print("4. 종료")
choice = input("선택 (1-4): ").strip()
if choice == "1":
print("\n샘플 텍스트 선택:")
for i, (name, _) in enumerate(sample_texts.items(), 1):
print(f" {i}. {name}")
sample_choice = input("선택 (1-3): ").strip()
if sample_choice in ["1", "2", "3"]:
text_name = list(sample_texts.keys())[int(sample_choice) - 1]
text = sample_texts[text_name].strip()
print(f"\n📝 분석 대상: {text_name}")
print(f"내용 미리보기: {text[:100]}...")
results = analyze_comprehensive(text)
display_analysis(results)
elif choice == "2":
print("\n텍스트를 입력하세요 (완료하려면 빈 줄 입력):")
lines = []
while True:
line = input()
if not line.strip():
break
lines.append(line)
if lines:
text = "\n".join(lines)
results = analyze_comprehensive(text)
display_analysis(results)
else:
print("❌ 텍스트가 입력되지 않았습니다.")
elif choice == "3":
filename = input("파일 이름을 입력하세요: ").strip()
try:
with open(filename, 'r', encoding='utf-8') as file:
text = file.read()
results = analyze_comprehensive(text)
display_analysis(results)
except FileNotFoundError:
print("❌ 파일을 찾을 수 없습니다.")
except Exception as e:
print(f"❌ 오류 발생: {e}")
elif choice == "4":
print("👋 텍스트 분석기를 종료합니다.")
break
else:
print("❌ 잘못된 선택입니다.")
# 텍스트 분석기 실행
# comprehensive_text_analyzer()
마무리 정리
이 가이드에서 우리는 파이썬 문자열의 핵심 개념들을 다음과 같이 학습했습니다:
주요 학습 내용
주제핵심 내용활용도문자열 생성 | 4가지 방법 (", ', """, ''') | ⭐⭐⭐⭐⭐ |
특수문자 처리 | 이스케이프 문자, 따옴표 포함 | ⭐⭐⭐⭐ |
문자열 연산 | 더하기, 곱하기, 길이 측정 | ⭐⭐⭐⭐⭐ |
인덱싱/슬라이싱 | 문자 접근, 부분 문자열 추출 | ⭐⭐⭐⭐⭐ |
문자열 메서드 | upper, lower, strip, split 등 | ⭐⭐⭐⭐ |
패턴 매칭 | find, replace, 검증 함수 | ⭐⭐⭐ |
성능 최적화 | join 활용, 메모리 효율성 | ⭐⭐⭐ |
실전 활용 팁
- 문자열 연결할 때: + 대신 join() 사용하기
- 대용량 텍스트: 청크 단위로 처리하기
- 사용자 입력 검증: 항상 예외 상황 고려하기
- 코드 가독성: f-string 적극 활용하기
이제 여러분은 파이썬 문자열을 자유자재로 다룰 수 있는 기초를 단단히 다졌습니다. 계속해서 실습하고 다양한 프로젝트에 적용해보시기 바랍니다!
python
# 마지막 격려 메시지
def final_message():
message = "파이썬 문자열 마스터가 되신 것을 축하합니다!"
border = "🎉" * len(message)
print(border)
print(message)
print(border)
print("이제 더 복잡한 프로그래밍 도전을 시작해보세요! 💪")
final_message()
반응형
'파이썬' 카테고리의 다른 글
4. 파이썬 튜플 기초부터 고급 활용까지 (0) | 2025.05.23 |
---|---|
3. 예제와 함께하는 초보의 파이썬 리스트 완전 정복 가이드 (0) | 2025.05.23 |
1. 파이썬 숫자형 자료형 완벽 가이드 | 정수형, 실수형, 8진수, 16진수, 사칙연산, 계산기, 숫자 맞추기 (0) | 2025.05.23 |