언어 Language/파이썬 Python

파이썬 문자열 추출 라이브러리 pygrok 사용 예: 이름 추출, 날짜 추출

Tap to restart 2021. 2. 5. 12:00
반응형

pygrok이란?

문자열을 쉽게 추출할 수 있는 라이브러리다.

 

A Python library to parse strings and extract information from structured/unstructured data

(출처: pygrok)

 

pygrok 페이지에 나온 문자열 추출 예제

from pygrok import Grok
text = 'gary is male, 25 years old and weighs 68.5 kilograms'
pattern = '%{WORD:name} is %{WORD:gender}, %{NUMBER:age} years old and weighs %{NUMBER:weight} kilograms'
grok = Grok(pattern)
data_dict = grok.match(text)
print(data_dict)

출력 결과

{'name': 'gary', 'gender': 'male', 'age': '25', 'weight': '68.5'}

 

날짜 추출

from pygrok import Grok

date_text = "2021년 3월 21일"
date_pattern = '%{YEAR:year}년 %{MONTHNUM:month}월 %{MONTHDAY:day}일'
grok = Grok(date_pattern)
date_dict = grok.match(date_text)
print(date_dict)

출력 결과

{'year': '2021', 'month': '3', 'day': '21'}

 

만약 03 01 형태로 입력한다면?

from pygrok import Grok

date_text = "2021년 03월 01일"
date_pattern = '%{YEAR:year}년 %{MONTHNUM:month}월 %{MONTHDAY:day}일'
grok = Grok(date_pattern)
date_dict = grok.match(date_text)
print(date_dict)

출력 결과

{'year': '2021', 'month': '03', 'day': '01'}

 

만약 13월이라고 입력한다면?

from pygrok import Grok

date_text = "2021년 13월 01일"
date_pattern = '%{YEAR:year}년 %{MONTHNUM:month}월 %{MONTHDAY:day}일'
grok = Grok(date_pattern)
date_dict = grok.match(date_text)
print(date_dict)

아무 것도 출력되지 않는다.

date_dict의 type은 NoneType이다.

 

만약 32일이라고 입력한다면?

from pygrok import Grok

date_text = "2021년 1월 32일"
date_pattern = '%{YEAR:year}년 %{MONTHNUM:month}월 %{MONTHDAY:day}일'
grok = Grok(date_pattern)
date_dict = grok.match(date_text)
print(date_dict)

아무 것도 출력되지 않는다.

 

pygrok-example.ipynb
0.00MB

 

반응형