64 lines
2.7 KiB
Python
64 lines
2.7 KiB
Python
from googletrans import Translator
|
|
from img_trans.src.deepl import trans
|
|
from translatepy import Translator
|
|
|
|
def translate_texts_google(texts, src_lang='zh-cn', dest_lang='ko'):
|
|
"""텍스트 리스트를 지정된 언어에서 다른 언어로 번역"""
|
|
translated_texts = []
|
|
translator = Translator()
|
|
print(f"texts ======== {texts}")
|
|
print(f"texts number ======== {len(texts)}")
|
|
try:
|
|
translations = translator.translate(texts, src=src_lang, dest=dest_lang)
|
|
translated_texts = [translation.text for translation in translations]
|
|
except AttributeError as e:
|
|
print(f"번역 실패: Google 번역 API의 내부 변경으로 인해 번역을 수행할 수 없습니다. : {e}")
|
|
return translated_texts
|
|
|
|
|
|
def translate_texts_deepl(texts):
|
|
"""텍스트 리스트를 지정된 언어에서 다른 언어로 번역"""
|
|
# 텍스트 리스트를 엔터로 구분된 하나의 문자열로 합침
|
|
combined_text = "\n".join(texts)
|
|
|
|
# DeepL로 전체 텍스트 번역
|
|
try:
|
|
translated_combined_text = trans(combined_text)
|
|
for translation in translated_combined_text:
|
|
# "가격"이 포함된 경우 빈 문자열로 대체
|
|
translated_texts.append(translation.text if "가격" not in translation.text else "")
|
|
# 번역된 전체 텍스트를 엔터를 기준으로 분리하여 리스트로 만듦
|
|
translated_texts = translated_combined_text.split("\n")
|
|
except AttributeError as e:
|
|
print(f"번역 실패: {e}")
|
|
translated_texts = []
|
|
|
|
return translated_texts
|
|
|
|
|
|
def translate_texts_translatepy(texts, src_lang='zh-cn', dest_lang='ko'):
|
|
"""translatepy 라이브러리를 사용하여 텍스트 리스트를 번역합니다."""
|
|
translator = Translator()
|
|
translated_texts = []
|
|
print(f"번역대상 텍스트 숫자 ======== {len(texts)}")
|
|
print(f"번역대상 텍스트 ======== {texts}")
|
|
|
|
for text in texts:
|
|
result = translator.translate(text, source_language=src_lang, destination_language=dest_lang)
|
|
translation = str(result)
|
|
# "가격"이 포함된 경우 빈 문자열로 대체
|
|
translated_texts.append(translation if "가격" not in translation else "")
|
|
|
|
print(f"번역된 감지 텍스트 \n {translated_texts}")
|
|
|
|
return translated_texts
|
|
|
|
# # 사용 예
|
|
# texts = ["Hello, world!", "This is a test translation."]
|
|
# translated_texts = translate_texts_translatepy(texts, src_lang='en', dest_lang='ko')
|
|
# for text, translated in zip(texts, translated_texts):
|
|
# print(f'{text} => {translated}')
|
|
|
|
# text='老顾客多次回购'
|
|
# trans_ted = translate_texts_deepl(text)
|
|
# print(f"trans_ted : {trans_ted}") |