Skip to main content

한글 유틸 패키지

Project description

py-hangul-utils

JS로 된 프로젝트를 파이썬으로 변환한 라이브러리입니다.

한글의 자모음의 분리,결합,검색 및 날짜와 숫자를 한글로 변환하는 등의 한글 기능 라이브러리입니다.

설치

pip install py-hangul-utils

Functions

한글 분리

divide_hangul(word: str, is_split: bool = True)

from hangul_utils import divide_hangul

divide_hangul("값싼")
# ['ㄱ', 'ㅏ', 'ㅂ', 'ㅅ', 'ㅆ', 'ㅏ', 'ㄴ']

문자를 초성, 중성, 종성으로 분리한 후 배열에 담아 반환해줍니다.

divide_hangul("값싼", False)
# ['ㄱ', 'ㅏ', 'ㅄ', 'ㅆ', 'ㅏ', 'ㄴ]

isSplit 타입이 False이면 중성, 종성 값이 분리되지 않습니다.

from hangul_utils import divide_hangul_by_groups

divide_hangul_by_groups("값싼")
# [ ['ㄱ', 'ㅏ', 'ㅂ', 'ㅅ'], ['ㅆ', 'ㅏ', 'ㄴ'] ]

divide_hangul_by_groups("값싼", is_split=False)
# [ ['ㄱ', 'ㅏ', 'ㅄ'], ['ㅆ', 'ㅏ', 'ㄴ'] ]

divide_hangul_by_groups함수는 한글자별 분리된 글자가 배열에 묶여 반환됩니다.

from hangul_utils import divide_hangul_by_groups

divide_hangul_by_groups("값싼", result_type="dict")
# [ {cho: 'ㄱ', jung: 'ㅏ', jong: 'ㅂㅅ'}, {cho: 'ㅆ', jung: 'ㅏ', jong: 'ㄴ'} ]

result_type으로는 'dict' | 'list' | 'str' | 'index' 타입이 존재하며, 기본은 'list' 타입으로 반환됩니다.

그 외

from hangul_utils import divide_by_jung, divide_by_jong

divide_by_jung("ㅝ")
# ㅜㅓ

divide_by_jong("ㄺ")
# ㄹㄱ

중성, 종성을 분리해줍니다.

한글 결합

combine_hangul(word: Union[str, List[str]])

from hangul_utils import combine_hangul

combine_hangul("ㅇㅏㄴㄴㅕㅇ")
# 안녕

combine_hangul(["ㄱ", "ㅏ", "ㅂ", "ㅅ", "ㅆ", "ㅏ", "ㄴ"])
# 값싼

문자를 한글로 결합하여 반환합니다.

combine_hangul([["ㄱ", "ㅏ", "ㅂ"], "ㅅ", "ㅏ"])
# 갑사

2차원 배열로 결합할 그룹을 지정할 수 있습니다.

그 외

from hangul_utils import combine_by_jung, combine_by_jong

combine_by_jung("ㅜㅓ")
# ㅝ

combine_by_jong("ㄹㄱ")
# ㄺ

중성, 종성을 결합해줍니다.

초성검색

includes_by_cho(search: str, word: str)

from hangul_utils import includes_by_cho

includes_by_cho("ㅅㄱ", "사과")
# True

includes_by_cho("ㅅ고", "사과")
# False

문자를 초성검색 정규식으로 변환하여 비교한 결과를 반환합니다.

import re
from hangul_utils import make_regex_by_cho

regex = make_regex_by_cho("ㅅㄱ")
# re.compile('([사-싷][가-깋])')

input_string = "사과수박"
re.sub(regex, r"<mark>\g<0></mark>", input_string)
# <mark>사과</mark>수박

문자를 초성 정규식으로 변환시켜 반환됩니다. (초성 정규식을 사용할 수 있습니다.)

숫자를 한글로

format_number(format: Optional[Union[int, str]])

from hangul_utils import format_number, format_number_all

format_number(123456789)
# 1억 2345만 6789

format_number_all(123456789)
# 일억 이천삼백사십오만 육천칠백팔십구

숫자를 한글로 변환 시켜 주는 함수입니다.

날짜 포맷

format_date(date: Union[str, datetime], format_style: str)

from datetime import datetime
from hangul_utils import format_date

format_date("2024-12-25 12:25:31")
# 2024년12월25일 12시25분31초

format_date(datetime.fromisoformat("2024-12-25 12:25:31"))
# 2024년12월25일 12시25분31초

format_date("2024-12-25", "YYYY년 MM월 DD일")
# 2024년 12월 25일

날짜를 주어진 formatStyle 형식에 맞춰서 변환시켜줍니다.

비슷한 단어 찾기

correct_by_distance(word: str, word_list: List[str], is_split: Optional[bool], distance: Optional[int], max_slice: Optional[int])

from hangul_utils import correct_by_distance

correct_by_distance("사과", ["사자", "호랑이", "사고"])
# [ '사고', '사자' ]

레벤슈타인 거리 알고리즘을 이용하여 단어 근접수치를 비교해 반환해줍니다.

옵션지정

correct_by_distance("number", ["number", "str", "bool"], distance=4, max_slice=1, is_split=False)
# [ 'number' ]

옵션을 지정하여 필터되는 수치를 조절하거나, 한글분해 작업을 해제할 수 있습니다.

문자 정렬

sort_by_asc(array: List[Any], compare: Union[List[str], str])

from hangul_utils import sort_by_asc, sort_by_desc

sort_by_asc(["사과", "귤", "바나나"])
# [ "귤", "바나나", "사과" ]

sort_by_desc(["사과", "귤", "바나나"])
# [ "사과", "바나나", "귤" ]

[예정] 문자(한글,영어)를 ASC(오름차순), DESC(내림차순) 정렬시켜줍니다.

array = [
  { 'name': ['귤'], 'age': 72 },
  { 'name': ['사과'], 'age': 25 },
  { 'name': ['귤'], 'age': 45 },
]

sort_by_asc(array, ["name", "age"])
# [{'name': ['귤'], 'age': 25}, {'name': ['귤'], 'age': 72}, {'name': ['사과'], 'age': 45}]

compare의 값으로 객체의 값을 특정할 수 있습니다. (배열 - 다중조건)

별도의 조건 지정하기

sort_by_groups(array: List[Any], groups: List[Union[int, str]], order_asc: bool, compare: Optional[str])

from hangul_utils import sort_by_groups

groups = ["회장", "사장", "부장", "대리", "사원"]

sort_by_groups(["대리", "사원", "사장", "회장", "부장"], groups)
# [ '회장', '사장', '부장', '대리', '사원' ]

특정 배열을 기준으로 정렬을 시켜줄 수 있습니다.

기존 정렬 로직상 '회장'은 '사원'보다 뒤에 위치해야하지만, 기준배열으로 인해서 앞에 위치합니다.


한영 변환

convert_key(word: str, to_language: Literal['ko', 'en'], is_combine: bool = True)

from hangul_utils import convert_key

convert_key("사과", "en")
# tkrhk

convert_key("tkrhk", "ko")
# 사과

to_language 타입 키보드 키 에 맞게 문자를 변환시켜줍니다.

convert_key("tkrhk", "ko", False)
# ㅅㅏㄱㅗㅏ

isCombine 속성을 비활성화 할 시, 한글이 결합되지 않습니다.

한글 발음 파싱

normalize(text: str, is_space: bool)

from hangul_utils import normalize

normalize("이탈리아")
# 'i tar ri a'

normalize("이탈리아", False)
# 'itarria'

한글 발음을 영어로 변환하여줍니다.

조사

format_josa(word: str)

from hangul_utils import format_josa

format_josa("인생[이란/란]")
# '인생이란'

format_josa("인생[란/테스트]")
# '인생이란'

단어[조사1/조사2] 형식의 텍스트를 단어[조사]로 알맞게 변환됩니다.

'은/는', '이/가'와 같은 많이 알려진 조사는 자동으로 포맷됩니다. [란/테스트] -> [이란/란]

그 외

josa(word: str, josa: str)

from hangul_utils import josa

josa("인생", "란")
# '이란'

단어에 따른 조사 정보만을 반환 받습니다.

문자 암호화

encode(input: any), decode(input: any)

from hangul_utils import encode, decode

encode("테스트123")
# 1VWV5U1VsV1JrcEVWVlU0Ymt...

encode(["바나나", "자두", "귤"])
# 3Mnl6SlRJMVNqUURWbFFVU2p...

문자를 암호화 시켜주며 객체와 배열 데이터도 암호화 대상입니다.

encode1 = encode("테스트123")
decode(encode1)
# 테스트123

encode2 = encode(["바나나", "자두", "귤"])
decode(encode2)
# ['바나나', '자두', '귤']

encode로 변환된 암호문자를 decode 함수로 복호화 시킬 수 있습니다.

언어 구별

get_local_by_groups(word: str, is_percent: bool)

from hangul_utils import get_local_by_groups

get_local_by_groups("a1")
# ['en', 'number']

각 문자에 대한 언어를 배열에 담아서 반환해줍니다.

get_local_by_groups("안녕하세요! Hello, world! 1234 #", True)
# {'ko': 18.52, 'en': 37.04, 'number': 14.81, 'special': 29.63, 'etc': 0.0}

is_percent 값을 통해서, 언어가 사용된 퍼센트를 나타내는 객체를 반환 받을 수 있습니다.

is_hangul, is_cho, is_jung, is_jong

is_hangul(word: str), is_hangul_groups(word: str)

from hangul_utils import is_hangul, is_cho, is_jung, is_jong

is_hangul("사과")
# True

is_cho("ㅅㄱ")
# True

is_jung("ㅏㅘ")
# True

is_jong("ㄳ")
# True

입력된 문자가 한글, 초성, 중성, 종성인지 판별합니다.

from hangul_utils import is_hangul_by_groups, is_cho_by_groups, is_jung_by_groups, is_jong_by_groups

is_hangul_by_groups("사!")
# [True, False]

is_cho_by_groups("ㅅㅏ")
# [True, False]

is_jung_by_groups("ㅅㅘ")
# [False, True]

is_jong_by_groups("ㄳㅏㅅ")
# [True, False, True]

입력된 모든 문자의 한글, 초성, 중성, 종성 여부를 판별하여 배열에 담아 반환됩니다.

기타 함수(utils)

is_number

is_number(input: any)

from hangul_utils import is_number

is_number(None)
# False

is_number(0)
# True

입력값의 숫자 여부를 판별합니다.

reverse_by_object

reverse_by_object(object: any)

from hangul_utils import reverse_by_object

reverse_by_object({ 'a': 1, 'b': 2, 'c': 3 })
# { 1: 'a', 2: 'b', 3: 'c' }

객체의 Key, Value 값을 서로 바꿔 재구성한 데이터를 반환해줍니다.

get_nested_property

get_nested_property(key: Union[str, List[str]], object: any)

from hangul_utils import get_nested_property

object = { 'a': { 'b': 2 } }

object['a.b']
# error

get_nested_property("a.b", object)
# 2

object.a.b 접근을 문자열로 가능하도록 만들어주는 함수입니다.

chunk_at_end

chunk_at_end(value: str, n: int)

from hangul_utils import chunk_at_end

chunk_at_end("12345678", 4)
# [ '5678', '1234' ]

"".join(chunk_at_end("12345678", 1))
# '87654321'

문자를 뒤에서부터 n개씩 자른 아이템을 배열에 담아 반환해줍니다.

split_by_key

split_by_key(key: str)

from hangul_utils import split_by_key

split_by_key("a.b")
# ['a', 'b'];

split_by_key("a[5]")
# ['a', 5];

Key를 차례대로 구분한 값을 배열에 담아 반환해줍니다.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

py_hangul_utils-1.0.1.tar.gz (29.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

py_hangul_utils-1.0.1-py3-none-any.whl (24.6 kB view details)

Uploaded Python 3

File details

Details for the file py_hangul_utils-1.0.1.tar.gz.

File metadata

  • Download URL: py_hangul_utils-1.0.1.tar.gz
  • Upload date:
  • Size: 29.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.13.0

File hashes

Hashes for py_hangul_utils-1.0.1.tar.gz
Algorithm Hash digest
SHA256 6bc0dbf0ea10ee90af95f5a7752783932c1cecfed89328ded6f76a3dda4da57e
MD5 8be3966b62ef2e0ac87619b2ed114d60
BLAKE2b-256 c2fcec60763efb2a3bdea014bd3fbd484ba8611b670d605f3ecfc4a2f1831fe1

See more details on using hashes here.

File details

Details for the file py_hangul_utils-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for py_hangul_utils-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 367f19a9fb903030c7640518dbb7fbfd94516f0403eb3cddd453931a55cf416b
MD5 e99a9b166a182ccec0a043fa2297df46
BLAKE2b-256 f6042540f0cd312e9ca30dc3a1a5bcecbe65a4e0a627c60477ae8055bcc5eee2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page