본문 바로가기

스크립트

파이션 텍스트 처리

반응형

파이썬에서 텍스트를 처리하는 것은 매우 일반적이고 유용한 작업입니다. 주로 str 객체와 문자열 메서드를 사용하여 텍스트를 조작하고 처리합니다.

 

아래에는 일반적으로 사용되는 몇 가지 텍스트 처리 기술을 설명하겠습니다.

문자열 메서드

1. 문자열 분할 (Splitting Strings)

  • split() 메서드를 사용하여 문자열을 지정된 구분자로 분할할 수 있습니다.
>>> sentence = "Hello, world!"
>>> words = sentence.split()
>>> print(words) # ['Hello,', 'world!']
['Hello,', 'world!']

2. 문자열 결합 (Joining Strings)

  • join() 메서드를 사용하여 리스트의 문자열 요소를 결합할 수 있습니다.
>>> words = ['Hello,', 'world!']
>>> sentence = ' '.join(words)
>>> print(sentence) # "Hello, world!"
Hello, world!

3. 대소문자 변환 (Case Conversion)

  • upper() 및 lower() 메서드를 사용하여 대소문자를 변환할 수 있습니다.
>>> text = "Hello, World!"
>>> print(text.lower()) # "hello, world!"
hello, world!

4. 공백 제거 (Stripping Whitespace)

  • strip() 메서드를 사용하여 문자열의 앞뒤 공백을 제거할 수 있습니다.
>>> text = "  Hello, world!  "
>>> print(text.strip()) # "Hello, world!"
Hello, world!

5. 검색 및 치환 (Searching and Replacing)

  • find(), index() 등의 메서드를 사용하여 문자열을 검색하고, replace() 메서드를 사용하여 문자열을 치환할 수 있습니다.
>>> text = "Hello, world!"
>>> print(text.find("world")) # 7
7
>>> print(text.replace("world", "Python")) # "Hello, Python!"
Hello, Python!

6. 정규 표현식 (Regular Expressions)

  • 정규 표현식은 문자열에서 패턴을 검색하고 추출하는 강력한 도구입니다. 파이썬에서는 re 모듈을 사용하여 정규 표현식을 활용할 수 있습니다.
  • 패턴 매칭 (Pattern Matching)
    • 정규 표현식을 사용하여 텍스트에서 특정 패턴을 매칭하고 검색할 수 있습니다.
>>> import re
>>>
>>> text = "The quick brown fox jumps over the lazy dog"
>>>
>>> pattern = r'\b\w{3}\b' # 세 글자로 이루어진 단어
>>> matches = re.findall(pattern, text)
>>>
>>> print(matches) # ['The', 'fox', 'the', 'dog']
['The', 'fox', 'the', 'dog']
  • 문자열 대체 (String Replacement)
    • 정규 표현식을 사용하여 텍스트 내에서 패턴을 찾아 다른 문자열로 대체할 수 있습니다.
>>> import re
>>>
>>> text = "Hello, world! How are you?"
>>>
>>> pattern = r'world'
>>> new_text = re.sub(pattern, 'Python', text)
>>>
>>> print(new_text) # "Hello, Python! How are you?"
Hello, Python! How are you?
  • 문자열 분할 (String Splitting)
    • 정규 표현식을 사용하여 텍스트를 특정 패턴을 기준으로 분할할 수 있습니다.
>>> import re
>>>
>>> text = "apple,banana,grape,orange"
>>>
>>> pattern = r','
>>> words = re.split(pattern, text)
>>>
>>> print(words) # ['apple', 'banana', 'grape', 'orange']
['apple', 'banana', 'grape', 'orange']
  • 패턴 검색 (Pattern Searching)
    • 정규 표현식을 사용하여 특정 패턴이 텍스트에 존재하는지 확인할 수 있습니다.
>>> import re
>>>
>>> text = "The quick brown fox jumps over the lazy dog"
>>>
>>> pattern = r'fox'
>>> if re.search(pattern, text):
...     print("Found")
... else:
...     print("Not found")
... 
Found

 

위의 기능들을 조합하여 텍스트를 효과적으로 처리할 수 있습니다. 필요에 따라 각 메서드와 기능을 활용하여 텍스트 처리를 수행하면 됩니다.

 

반응형