Skip to main content

Tokenizer

Struct Tokenizer 

Source
pub struct Tokenizer { /* private fields */ }
Expand description

토크나이저

형태소 분석의 메인 인터페이스입니다. 시스템 사전, 사용자 사전, 미등록어 처리기를 통합하여 형태소 분석을 수행합니다.

§메모리 최적화

  • lattice 재사용으로 매 분석마다 재할당 방지
  • pool_manager로 Token, Node 객체 재사용
  • String interning으로 중복 문자열 제거

Implementations§

Source§

impl Tokenizer

Source

pub fn new() -> Result<Tokenizer, Error>

기본 사전으로 토크나이저 생성

환경변수 MECAB_DICDIR이나 기본 경로에서 시스템 사전을 로드합니다.

§Errors
  • 사전을 찾을 수 없는 경우
  • 사전 파일 포맷이 잘못된 경우
§Example
use mecab_ko_core::tokenizer::Tokenizer;

let mut tokenizer = Tokenizer::new().unwrap();
let tokens = tokenizer.tokenize("안녕하세요");
Source

pub fn with_dict<P>(dict_path: P) -> Result<Tokenizer, Error>
where P: AsRef<Path>,

사전 경로를 지정하여 토크나이저 생성

§Arguments
  • dict_path - 사전 디렉토리 경로
§Errors
  • 사전을 찾을 수 없는 경우
  • 사전 파일 포맷이 잘못된 경우
Source

pub fn with_user_dict(self, user_dict: UserDictionary) -> Tokenizer

사용자 사전 추가

§Arguments
  • user_dict - 사용자 사전
§Example
use mecab_ko_core::tokenizer::Tokenizer;
use mecab_ko_dict::UserDictionary;

let mut user_dict = UserDictionary::new();
user_dict.add_entry("딥러닝", "NNG", Some(-1000), None);

let tokenizer = Tokenizer::new().unwrap()
    .with_user_dict(user_dict);
Source

pub fn set_user_dict(&mut self, user_dict: UserDictionary)

사용자 사전 설정 (in-place)

이미 생성된 토크나이저에 사용자 사전을 설정합니다. 빌더 패턴이 필요 없는 경우 사용합니다.

§Arguments
  • user_dict - 사용자 사전
§Example
use mecab_ko_core::Tokenizer;
use mecab_ko_dict::UserDictionary;

let mut tokenizer = Tokenizer::new().unwrap();

let mut user_dict = UserDictionary::new();
user_dict.add_entry("챗GPT", "NNP", Some(-2000), None);
tokenizer.set_user_dict(user_dict);
Source

pub fn with_space_penalty(self, penalty: SpacePenalty) -> Tokenizer

띄어쓰기 패널티 설정

§Arguments
  • penalty - 띄어쓰기 패널티 설정
Source

pub fn tokenize(&mut self, text: &str) -> Vec<Token>

형태소 분석

입력 텍스트를 형태소 단위로 분석하여 Token 목록을 반환합니다.

§Arguments
  • text - 분석할 텍스트
§Returns

토큰 목록

§Example
let tokens = tokenizer.tokenize("아버지가방에들어가신다");
for token in tokens {
    println!("{}: {}", token.surface, token.pos);
}
Source

pub fn tokenize_to_lattice(&mut self, text: &str) -> &Lattice

Lattice를 반환하여 검사

Viterbi 탐색 전의 Lattice 상태를 반환합니다. (디버깅/테스트용)

§Arguments
  • text - 분석할 텍스트
§Returns

구축된 Lattice

Source

pub fn wakati(&mut self, text: &str) -> Vec<String>

표면형만 추출 (wakati)

§Arguments
  • text - 분석할 텍스트
§Returns

분리된 표면형 목록 (wakati gaki)

일본어 형태소 분석기의 wakati gaki 모드와 동일합니다. 형태소로 분리된 표면형만 반환합니다.

§Arguments
  • text - 분석할 텍스트
§Returns

분리된 표면형 목록

§Example
use mecab_ko_core::Tokenizer;

let mut tokenizer = Tokenizer::new().unwrap();
let surfaces = tokenizer.wakati("아버지가방에들어가신다");
// ["아버지", "가", "방", "에", "들어가", "신다"]
Source

pub fn nouns(&mut self, text: &str) -> Vec<String>

명사만 추출

§Arguments
  • text - 분석할 텍스트
§Returns

명사 목록

Source

pub fn morphs(&mut self, text: &str) -> Vec<String>

형태소 목록 추출

wakati와 동일한 기능입니다. Python의 KoNLPy 인터페이스와 호환됩니다.

§Arguments
  • text - 분석할 텍스트
§Returns

형태소 목록

Source

pub fn pos(&mut self, text: &str) -> Vec<(String, String)>

품사 태깅

형태소와 품사 태그 쌍을 반환합니다. Python의 KoNLPy 인터페이스와 호환됩니다.

§Arguments
  • text - 분석할 텍스트
§Returns

(표면형, 품사) 쌍의 벡터

§Example
use mecab_ko_core::Tokenizer;

let mut tokenizer = Tokenizer::new().unwrap();
let tagged = tokenizer.pos("아버지가방에들어가신다");
// [("아버지", "NNG"), ("가", "JKS"), ("방", "NNG"), ...]
Source

pub const fn dictionary(&self) -> &SystemDictionary

시스템 사전 참조 반환

내부 시스템 사전에 대한 읽기 전용 참조를 반환합니다. 사전 정보 조회나 디버깅에 유용합니다.

Source

pub fn lattice_stats(&self) -> LatticeStats

Lattice 통계 정보

마지막 분석에서 생성된 Lattice의 통계 정보를 반환합니다. 노드 수, 엣지 수 등 디버깅 및 프로파일링에 유용합니다.

Source

pub fn pool_stats(&self) -> PoolStats

메모리 풀 통계 정보

메모리 풀의 사용 현황을 반환합니다.

Source

pub fn memory_stats(&self) -> MemoryStats

메모리 사용량 통계

토크나이저의 메모리 사용 현황을 반환합니다.

Source

pub fn clear_pools(&self)

메모리 풀 초기화

모든 풀을 비워 메모리를 해제합니다. 장기 실행 프로세스에서 주기적으로 호출하여 메모리 누수 방지.

Source

pub fn set_normalization( &mut self, enable: bool, config: Option<NormalizationConfig>, ) -> Result<(), Error>

외래어 정규화 활성화

§Arguments
  • enable - 정규화 활성화 여부
  • config - 정규화 설정 (None이면 기본 설정 사용)
§Errors

정규화기 초기화 실패 시 에러 반환

Source

pub const fn normalizer(&self) -> Option<&Normalizer>

외래어 정규화기 참조 반환

Source

pub const fn is_normalization_enabled(&self) -> bool

정규화가 활성화되어 있는지 확인

Source

pub fn tokenize_with_normalization(&mut self, text: &str) -> Vec<Token>

정규화 적용 형태소 분석

토큰의 표면형에 대해 정규화를 적용하고, 정규화된 형태도 함께 반환합니다.

§Arguments
  • text - 분석할 텍스트
§Returns

정규화 정보가 포함된 토큰 목록

Source

pub fn get_word_variants(&self, word: &str) -> (String, Vec<String>)

변이형 확장 검색

입력 단어의 변이형들을 모두 고려하여 사전 검색을 수행합니다.

§Arguments
  • word - 검색할 단어
§Returns

(표준형, [변이형들]) 튜플

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.