본문 바로가기

파이썬 python/파이썬 활용

[python] 파이썬 영어 문서를 한글로 번역하는 자동화 프로그램 만들기

안녕하세요 ! 

이번 포스팅에서는 영어 문서를 한글로 번역하는 자동화 프로그램을 만들어보도록 하겠습니다. 

 

우선, 번역하려고 하는 영어 문서를 텍스트 파일로 저장합니다. 

자동화 프로그램 전체 코드 ! 

1. 필요한 모듈 임포트 하기 

from os import linesep 
import googletrans

2. translator 객체 만들고, 파일 읽어오기 

translator = googletrans.Translator()

read_file_path = "eng_document.txt"

with open(read_file_path, 'rt', encoding='utf8') as f:
        readLines = f.readlines()

 

현재는 파일이 하나이므로 상대 경로 쓸 필요 없이, 파일 명만 적어주면 된다. 

with open(파일 경로, 'r') as f: 로 읽어오기 ! 

이때 'rt'의 t는 텍스트 모드를 나타낸다. 텍스트 모드가 기본 값이기 때문에 r과 rt간의 차이는 없다. readLines = f.readlines(), readlines() 함수로 한 줄 씩 읽어오고, 읽어온 값 readLines에 리스트로 저장하기 

 

3. 리스트 형태의 readLines에서 한줄씩 한글로 변환하여 출력하기 

for line in readLines:
     if line != "\n":
        result = translator.translate(line, dest="ko") 
        print(result.text)

만약 line이 엔터 공백이 아니라면, translate 하기 !

line을 한국어로 바꿔줄 것이므로 dest = "ko"

 

 

< 프로그램 만들면서 생긴 오류 >

 

1. IndexError : list index out of range 

File "c:\Users\User\Desktop\make python\translate.py", line 12, in <module> result = ranslator.translate(line, dest ="ko") File "C:\Users\User\anaconda3\lib\site-packages\googletrans\client.py", line 222, in translate translated_parts = list(map(lambda part: TranslatedPart(part[0], part[1] if len(part) >= 2 else []), parsed[1][0][0][5])) File "C:\Users\User\anaconda3\lib\site-packages\googletrans\client.py", line 222, in <lambda> translated_parts = list(map(lambda part: TranslatedPart(part[0], part[1] if len(part) >= 2 else []), parsed[1][0][0][5]))IndexError: list index out of range

googletrans 가 빈줄을 어떻게 처리해야할지 모르기 때문에 생긴 오류 

 

(1) eng_document의 빈줄을 삭제해주면 된다. 

(2) if line != "\n" 코드 추가해주기 

위의 코드를 추가해주면, line 이 엔터가 (\n) 아닐때만, googletrans의 translate로 번역을 해서 오류를 막아준다. 

 

2. unicodedecodeerror 유니코드 에러 

UnicodeDecodeError: 'cp949' codec can't decode byte 0xe2 in position 168: illegal multibyte sequence

이 문제는 cp949 코덱으로 인코딩 된 파일을 읽어들일때 생기는 문제라고 한다.

with open("파일명", "rt", encoding = "UTF8")로 코드를 수정하여 해결할 수 있다!

 

+ 자동화 프로그램으로 만든 내용을 저장하기 위한 코드 

7번째 줄에 저장할 파일명을 정해주고, 

마지막 줄에 저장할 파일을 열어서 번역한 내용을 한 줄씩 append 추가해주는 코드를 넣어주면 된다. 

with open(write_file_path, 'a', encoding='utf8') as f:
       f.write(result.text +'\n')

이때, result 뒤에 text를 붙이지 않으면 오류가 나는 걸 볼 수 있다. 

그 이유는 

print( type(result))을 해보면, 

<class 'googletrans.models.Translated'>라고 뜨기 때문이다.

= +와 결합하기 위해서는, 문자열이어야 하는데, result의 type은 클래스의 객체이기 때문이다! 

이 문제를 해결하기 위해서, result 뒤에 text를 붙여서 문자열로 처리해주는 것이다 ~ 

 

후후,,, 이번 포스팅은 여기서 끝 !