강의계획서에서 텍스트를 읽어 정보를 정리하고, 일정을 자동으로 등록해주는 어플리케이션 만들기.
그 중 강의계획서에서 텍스트를 읽어 정보를 정리하는 파트를 구현해볼 예정이다.
1. word, pdf, hwp 등 강의 계획서를 jpg로 바꾸기
2-1. jpg 파일에서 ocr을 통해 text 추출하기
2-2. text를 추출할 때 정규식을 통해 필요한 정보만 가져온다.
3-1. 일부 text는 정제과정 없이 DB에 저장한다.
3-2. 일부 text는 정제한 후 자연어처리하여 요약 후 DB에 저장한다.
이번 포스트에선 다양한 형식의 강의 계획서 파일을 jpg 파일로 변환하는 코드를 구현할 것이다. 파이썬으로 구현할 것이며, 함수는 총 5개이다.
import os
import comtypes
import ntpath
from pdf2jpg import pdf2jpg
import pywin32
word_to_pdf, hwp_to_pdf
import os
from contextlib import suppress
def pdf_to_jpg(file):
#파라미터로 pdf 파일의 절대경로를 받는다.
dest = os.path.dirname(file)
if not os.path.isdir(dest):
os.mkdir(dest)
pdf2jpg.convert_pdf2jpg(file, dest, dpi = 300, pages ='ALL')
#pdf가 여러 장으로 되어있다면 모든 장을 jpg로 바꾼다.
import os
import comtypes
import ntpath
from pdf2jpg import pdf2jpg
def word_to_pdf(file):
#파라미터로 pdf 파일의 절대경로를 받는다.
dest = os.path.dirname(file)
word = comtypes.client.CreateObject('Word.Application')
word.Visible = False
doc = word.Documents.Open(file)
file_name = ntpath.basename(file)
output_file_path = os.path.join(dest, file_name + ".pdf")
doc.SaveAs(output_file_path, FileFormat=17)
doc.Close()
return output_file_path
def word_to_jpg(file):
with suppress(KeyError): pdf_to_jpg(word_to_pdf(file))
#실행하면 에러는 뜨는데 실행되긴 됨. 무슨 에러인지를 모르겠음...
import pywin32
def hwp_to_pdf(file):
dest = os.path.dirname(file)
hwp = pywin32.client.gencache.EnsureDispatch('HWPFrame.HwpObject')
hwp.RegisterModule('FilePathCheckDLL', 'SecurityModule')
hwp.Open(os.path.join(dest, file))
hwp.HAction.GetDefault("FileSaveAs_S", hwp.HParameterSet.HFileOpenSave.HSet)
pre, ext = os.path.splitext(file)
hwp.HParameterSet.HFileOpenSave.filename = os.path.join(dest,pre + ".pdf")
hwp.HParameterSet.HFileOpenSave.Format = "PDF"
hwp.HAction.Execute("FileSaveAs_s", hwp.HParameterSet.HFileOpenSave.HSet)
hwp.Quit()
import win32com.client as win32
def hwp_to_pdf(file):
hwp = win32.gencache.EnsureDispatch('HWPFrame.HwpObject')
hwp.RegisterModule('FilePathCheckDLL', 'SecurityModule')
hwp.Open(file)
hwp.HAction.GetDefault("FileSaveAs_S", hwp.HParameterSet.HFileOpenSave.HSet)
hwp.HParameterSet.HFileOpenSave.filename = os.path.join(file, ".pdf")
hwp.HParameterSet.HFileOpenSave.Format = "PDF"
hwp.HAction.Execute("FileSaveAs_S", hwp.HParameterSet.HFileOpenSave.HSet)
hwp.Quit()
return hwp.HParameterSet.HFileOpenSave.filename
def hwp_to_jpg(file):
pdf_to_jpg(hwp_to_pdf(file))
함수 안에 파일이 저장되어있는 위치랑 이름만 작성하고 실행하면 되나요??