디시인사이드 갤러리

마이너 갤러리 이슈박스, 최근방문 갤러리

갤러리 본문 영역

[free] html 파일 분할 (장 나누기)

몬발켜갤로그로 이동합니다. 2025.02.21 04:35:34
조회 24 추천 0 댓글 0

[마흔]이라는 소설을 번역해서 읽고 있습니다. 

이 소설의 앞 부분은 1장, 2장 장이 바뀔 때마다 html 파일이 달라졌습니다. 

그런데 중간에 2개의 장이 1개의 html 파일 안에 같이 들어 있는 경우가 많이 있었습니다. 

때로는 3개의 장이 같이 들어 있는 경우도 있었습니다. 

제미나이 플래시 2.0의 출력 토큰은 8192이므로 번역이 중간에 잘리는 경우가 자주 발생했습니다. 

매우 귀찮았습니다. 

그래서 2개의 장이 1개의 html 파일로 되어 있는 경우에 파일을 분할하는 프로그램을 만들려고 했습니다. 


1. 사용자는 폴더를 선택합니다. 여기에 html 피일들이 들어 있습니다. 

2. 사용자는 '파일 분할' 버튼을 클릭합니다. 그러면 분할 작업이 시작됩니다. 진행률 표시기가 바로 아래에 있습니다. 

3. 작업은 대충 이런 단계로 진행됩니다. 

 폴더의 파일명을 변수에 저장합니다. 

 파일을 열어서 '제123장'이라는 형식의 데이터를 찾습니다. 

파일의 시작~'제1123장'까지가 새로운 html 파일로 저장됩니다. 

저장되는 위치는 c:\output 폴더입니다. 

저장되는 파일의 이름은 0001.html에서 9999.html까지입니다. 

만약 output 폴더에 이미 다른 0003.html 파일이 있었다면, 그 다음 파일명인 0004.html로 저장하게 됩니다. 


프로그램을 실행해 보니, 완벽하게 분할되지 않는 현상도 발생하고 그렇습니다. 

그런데 왜 이런 현상이 발생하는지 이유를 지금 알 수가 없어서 수정은 더 못하고 있습니다.... ㅠ ㅠ 


chatGPT에게 물어서 만들었습니다. 

이 코드는 퍼블릭 도메인입니다.

누구나 마음대로 수정 가능하고, 남에게 복사해 줄 수 있고, 심지어 실행 프로그램을 만들어서 판매하셔도 됩니다. ^ ^ 


import sys
import os
import re
import shutil
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QFileDialog, QLabel, QProgressBar
from PyQt5.QtCore import QDir

class SplitterApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.selected_folder = None
        self.html_files = []

    def initUI(self):
        layout = QVBoxLayout()

        self.lbl = QLabel('선택한 폴더: 없음', self)
        layout.addWidget(self.lbl)

        btn_select_folder = QPushButton('폴더 선택', self)
        btn_select_folder.clicked.connect(self.select_folder)
        layout.addWidget(btn_select_folder)

        btn_split_files = QPushButton('파일 분할', self)
        btn_split_files.clicked.connect(self.split_files)
        layout.addWidget(btn_split_files)

        self.progressBar = QProgressBar(self)
        layout.addWidget(self.progressBar)

        self.setLayout(layout)
        self.setWindowTitle('HTML 파일 분할기')
        self.setGeometry(300, 300, 300, 200)

    def select_folder(self):
        folder = QFileDialog.getExistingDirectory(self, '폴더 선택', QDir.homePath())
        if folder:
            self.selected_folder = folder
            self.lbl.setText(f'선택한 폴더: {folder}')
            self.html_files = [f for f in os.listdir(folder) if f.endswith('.html')]

    def split_files(self):
        if not self.selected_folder or not self.html_files:
            self.lbl.setText('선택한 폴더에 적합한 HTML 파일이 없습니다.')
            return

        output_folder = r'c:\output'
        os.makedirs(output_folder, exist_ok=True)

        existing_files = [f for f in os.listdir(output_folder) if f.endswith('.html')]
        start_index = int(sorted(existing_files)[-1].split('.')[0]) + 1 if existing_files else 1

        total_files = len(self.html_files)
        self.progressBar.setMaximum(total_files)

        for index, html_file in enumerate(self.html_files, 1):
            file_path = os.path.join(self.selected_folder, html_file)
            with open(file_path, 'r', encoding='utf-8') as file:
                content = file.read()

            parts = re.split(r'(第[\d零一二三四五六七八九十百千万]+章)', content)
            if len(parts) > 1:
                # Save the content before the first chapter
                with open(os.path.join(output_folder, f'{start_index:04}.html'), 'w', encoding='utf-8') as new_file:
                    new_file.write(parts[0])
                start_index += 1

                # Save each chapter and the content following it until the next chapter
                for i in range(1, len(parts) - 1, 2):
                    chapter_title = parts[i]
                    chapter_content = parts[i + 1]
                    with open(os.path.join(output_folder, f'{start_index:04}.html'), 'w', encoding='utf-8') as new_file:
                        new_file.write(chapter_title + chapter_content)
                    start_index += 1

            # Progress bar update
            self.progressBar.setValue(index)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = SplitterApp()
    ex.show()
    sys.exit(app.exec_())

추천 비추천

0

고정닉 0

0

댓글 영역

전체 댓글 0
본문 보기

하단 갤러리 리스트 영역

왼쪽 컨텐츠 영역

갤러리 리스트 영역

갤러리 리스트
번호 말머리 제목 글쓴이 작성일 조회 추천
- 설문 현역으로 군대 안 간게 의아한 스타는? 운영자 25/06/30 - -
1 공지 프로그램 소스 코드의 공유/수정/판매 [2] 몬발켜갤로그로 이동합니다. 24.12.24 279 2
20 fre 빨간 공 파란 공 랜덤으로 그리는 프로그램 몬발켜갤로그로 이동합니다. 05.15 20 0
19 fre textmovie -자막만 있는 동영상 [2] 몬발켜갤로그로 이동합니다. 04.10 23 0
18 fre novel 9을 또 수정했습니다 몬발켜갤로그로 이동합니다. 02.27 17 0
fre html 파일 분할 (장 나누기) 몬발켜갤로그로 이동합니다. 02.21 24 0
16 fre 제미나이 복붙 novel 9을 또 수정했습니다 몬발켜갤로그로 이동합니다. 02.13 40 0
15 fre 제미나이 Flash 2.0을 위한 코드를 수정하였습니다 [4] 몬발켜갤로그로 이동합니다. 02.06 49 0
14 fre 1206, flash 1.5를 위한 코드를 수정했습니다 몬발켜갤로그로 이동합니다. 02.01 22 0
13 fre 누락된 파일명 찾아내기 몬발켜갤로그로 이동합니다. 01.31 12 0
12 fre 순서가 뒤죽박죽인 html 파일 이름 바꾸기 코드 몬발켜갤로그로 이동합니다. 01.31 27 0
11 fre 순서가 뒤죽박죽인 html 파일들 해결하기 몬발켜갤로그로 이동합니다. 01.30 27 0
10 fre 1206, Flash 1.5를 위한 코드를 또 수정했습니다 몬발켜갤로그로 이동합니다. 01.28 23 0
9 fre 1206 복붙 코드를 수정하였습니다 몬발켜갤로그로 이동합니다. 01.17 23 0
8 fre 1206을 위한 복붙 [2] 몬발켜갤로그로 이동합니다. 01.13 81 0
7 일반 이런갤도 있네 프갤러(223.38) 01.10 17 0
6 일반 북스캔 코드에 관한 설명을 추가합니다 몬발켜갤로그로 이동합니다. 01.09 56 0
5 fre 북스캔 book scan 몬발켜갤로그로 이동합니다. 01.07 213 1
4 fre 검색어로 폴더와 그 하위 폴더 안의 파일을 찾아주는 프로그램 몬발켜갤로그로 이동합니다. 24.12.24 127 0
3 fre 검색어로 폴더 안의 파일을 찾아주는 프로그램 [2] 몬발켜갤로그로 이동합니다. 24.12.24 188 0
2 fre 파일명이 (1)로 끝나는 파일만 찾아주는 프로그램 몬발켜갤로그로 이동합니다. 24.12.24 123 1
뉴스 스트레이 키즈 리노, 구찌 글로벌 앰버서더 발탁 디시트렌드 14:00
1
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2