AutoPercenty3/option_translator.py

117 lines
4.4 KiB
Python

import re
import jieba
from collections import Counter
from transformers import pipeline
class ProductOptionTranslator:
def __init__(self, product_name, options, translator):
"""
옵션 명칭을 간소화하고 번역하는 클래스.
Parameters:
- product_name (str): 상품명
- options (list): 옵션명 리스트 (중국어 원문)
- translator (object): 번역기 객체 (예: transformers의 pipeline 등)
"""
self.product_name = product_name
self.options = options
self.translator = translator
def simplify_options(self):
"""
각 옵션의 특징을 간결하게 남기고 불필요한 정보를 제거합니다.
Returns:
- simplified_options (list): 간소화된 옵션명 리스트
"""
# 상품명에서 공통적인 키워드 추출
common_words = self.extract_common_words()
simplified_options = []
for option in self.options:
# 형태소 분석을 통해 단어 단위로 분리
words = list(jieba.cut(option))
# 의미 있는 단어만 남기기 (숫자, 영어, 특수한 패턴 유지)
keywords = [word for word in words if self.is_significant(word, common_words)]
# 간결하게 옵션명 재구성
simplified_option = " ".join(keywords)
simplified_options.append(simplified_option)
return simplified_options
def extract_common_words(self):
"""
상품명에서 공통적으로 사용되는 키워드를 추출합니다.
Returns:
- common_words (set): 상품명에서 중복되는 일반적인 단어들의 집합
"""
product_words = list(jieba.cut(self.product_name))
word_counts = Counter(product_words)
common_words = {word for word, count in word_counts.items() if count > 1}
return common_words
def is_significant(self, word, common_words):
"""
단어가 의미 있는지 확인합니다. 의미 없는 수식어나 중복된 단어는 제거합니다.
Parameters:
- word (str): 검사할 단어
- common_words (set): 상품명에서 추출한 공통 단어들
Returns:
- (bool): 단어가 의미 있는 경우 True, 그렇지 않은 경우 False
"""
# 공통 단어 또는 의미 없는 수식어는 제거
if word in common_words:
return False
# 숫자, 영어 또는 특정 패턴(전압, 전류 등)은 의미 있는 단어로 간주
if re.match(r'[A-Za-z0-9]+', word) or re.match(r'\d+(V|A|W|Hz)', word):
return True
return True if len(word) > 1 else False
def translate_options(self, simplified_options):
"""
간소화된 옵션명을 한글로 번역합니다.
Parameters:
- simplified_options (list): 간소화된 옵션명 리스트
Returns:
- translated_options (list): 한글로 번역된 옵션명 리스트 (25자 이내로 축약)
"""
translated_options = []
for option in simplified_options:
translated_text = self.translator(option, src_lang="zh", tgt_lang="ko")
# 번역된 결과가 25자를 넘을 경우 축약
if len(translated_text) > 25:
translated_text = translated_text[:25] + '...'
translated_options.append(translated_text)
return translated_options
def process_options(self):
"""
전체 옵션 처리 과정을 수행합니다 (간소화 + 번역).
Returns:
- translated_options (list): 최종 한글로 번역된 옵션 리스트
"""
simplified_options = self.simplify_options()
return self.translate_options(simplified_options)
# 번역기 예시 (transformers의 pipeline을 사용한 경우)
translator = pipeline('translation', model='Helsinki-NLP/opus-mt-zh-ko')
# 예제 데이터
product_name = "전기 드릴 18V 가정용"
options = ["18V 2.0Ah 배터리 포함", "18V 본체만", "충전기 포함 세트", "전용 케이스"]
# 클래스 사용
translator_class = ProductOptionTranslator(product_name, options, translator)
translated_options = translator_class.process_options()
for idx, translated_option in enumerate(translated_options, 1):
print(f"옵션 {idx}: {translated_option}")