File size: 9,657 Bytes
3e6ca52 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 |
#!/usr/bin/env python3
"""
Script để xử lý và làm sạch dữ liệu từ thư mục raw/
"""
import os
import glob
from pathlib import Path
import re
# Cấu hình
RAW_DIR = "raw/documents"
PROCESSED_DIR = "processed"
SUPPORTED_EXTENSIONS = [".txt", ".md"]
def clean_text(text):
"""Làm sạch văn bản nhưng giữ lại cấu trúc"""
# Loại bỏ ký tự null
text = text.replace('\x00', '')
# Loại bỏ các ký tự điều khiển không cần thiết (nhưng giữ lại \n và \t)
text = re.sub(r'[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f-\x9f]', '', text)
# Loại bỏ khoảng trắng thừa ở đầu và cuối mỗi dòng (nhưng giữ lại xuống dòng)
lines = text.split('\n')
cleaned_lines = [line.strip() for line in lines]
text = '\n'.join(cleaned_lines)
# Loại bỏ nhiều dòng trống liên tiếp (chỉ giữ tối đa 2 dòng trống)
text = re.sub(r'\n{3,}', '\n\n', text)
# Loại bỏ khoảng trắng thừa trong cùng một dòng (nhưng không ảnh hưởng xuống dòng)
lines = text.split('\n')
cleaned_lines = []
for line in lines:
# Loại bỏ nhiều khoảng trắng liên tiếp trong dòng
cleaned_line = re.sub(r' +', ' ', line)
cleaned_lines.append(cleaned_line)
text = '\n'.join(cleaned_lines)
# Loại bỏ khoảng trắng ở đầu và cuối toàn bộ văn bản
text = text.strip()
return text
def process_text_file(input_path, output_dir):
"""Xử lý một file text"""
try:
with open(input_path, 'r', encoding='utf-8') as f:
content = f.read()
except UnicodeDecodeError:
# Thử với encoding khác
try:
with open(input_path, 'r', encoding='latin-1') as f:
content = f.read()
except Exception as e:
print(f"Lỗi khi đọc file {input_path}: {e}")
return False
# Làm sạch văn bản
cleaned_content = clean_text(content)
if not cleaned_content:
print(f"File {input_path} rỗng sau khi làm sạch")
return False
# Tạo tên file output
input_filename = Path(input_path).stem
output_path = os.path.join(output_dir, f"{input_filename}.txt")
# Lưu file đã xử lý
with open(output_path, 'w', encoding='utf-8') as f:
f.write(cleaned_content)
print(f"Đã xử lý: {input_path} -> {output_path}")
return True
def process_pdf_file(input_path, output_dir):
"""Xử lý file PDF"""
try:
import pdfplumber
except ImportError:
print("Cần cài đặt pdfplumber: pip install pdfplumber")
return False
try:
content = ""
with pdfplumber.open(input_path) as pdf:
for page in pdf.pages:
page_text = page.extract_text()
if page_text:
content += page_text + "\n"
if not content.strip():
print(f"Không thể extract text từ PDF: {input_path}")
return False
# Làm sạch văn bản
cleaned_content = clean_text(content)
# Tạo tên file output
input_filename = Path(input_path).stem
output_path = os.path.join(output_dir, f"{input_filename}.txt")
# Lưu file đã xử lý
with open(output_path, 'w', encoding='utf-8') as f:
f.write(cleaned_content)
print(f"Đã xử lý PDF: {input_path} -> {output_path}")
return True
except Exception as e:
print(f"Lỗi khi xử lý PDF {input_path}: {e}")
return False
def process_docx_file(input_path, output_dir):
"""Xử lý file DOCX - Extract toàn bộ nội dung"""
try:
from docx import Document
from docx.oxml.text.paragraph import CT_P
from docx.oxml.table import CT_Tbl
from docx.table import _Cell, Table
from docx.text.paragraph import Paragraph
except ImportError:
print("Cần cài đặt python-docx: pip install python-docx")
return False
try:
doc = Document(input_path)
content = ""
# Extract text từ tất cả paragraphs (bao gồm cả trong headers/footers)
for paragraph in doc.paragraphs:
para_text = paragraph.text.strip()
if para_text:
content += para_text + "\n"
# Extract text từ headers
for section in doc.sections:
if section.header:
for paragraph in section.header.paragraphs:
para_text = paragraph.text.strip()
if para_text:
content += para_text + "\n"
if section.footer:
for paragraph in section.footer.paragraphs:
para_text = paragraph.text.strip()
if para_text:
content += para_text + "\n"
# Extract text từ tables (bao gồm cả nested tables)
def extract_table_text(table):
"""Recursively extract text from table including nested tables"""
table_text = ""
for row in table.rows:
row_texts = []
for cell in row.cells:
# Extract text from paragraphs in cell
cell_text = ""
for para in cell.paragraphs:
if para.text.strip():
cell_text += para.text.strip() + " "
# Check for nested tables in cell
for nested_table in cell.tables:
cell_text += extract_table_text(nested_table) + " "
if cell_text.strip():
row_texts.append(cell_text.strip())
if row_texts:
table_text += " | ".join(row_texts) + "\n"
return table_text
for table in doc.tables:
table_content = extract_table_text(table)
if table_content.strip():
content += "\n" + table_content + "\n"
# Extract text từ inline shapes (text boxes) nếu có
# Lưu ý: python-docx không hỗ trợ extract text boxes trực tiếp
# Nhưng chúng ta có thể thử extract từ XML
try:
from docx.oxml import parse_xml
# Tìm text trong các phần tử khác
for element in doc.element.body.iter():
if element.tag.endswith('}t'): # Text element
if element.text:
text = element.text.strip()
if text and text not in content:
# Chỉ thêm nếu chưa có trong content (tránh duplicate)
pass
except:
pass # Bỏ qua nếu không extract được
if not content.strip():
print(f"Không thể extract text từ DOCX: {input_path}")
return False
# Làm sạch văn bản (nhưng giữ lại cấu trúc)
cleaned_content = clean_text(content)
# Tạo tên file output
input_filename = Path(input_path).stem
output_path = os.path.join(output_dir, f"{input_filename}.txt")
# Lưu file đã xử lý
with open(output_path, 'w', encoding='utf-8') as f:
f.write(cleaned_content)
# Thống kê
original_size = os.path.getsize(input_path)
processed_size = len(cleaned_content.encode('utf-8'))
print(f"Đã xử lý DOCX: {input_path} -> {output_path}")
print(f" - Kích thước gốc: {original_size:,} bytes")
print(f" - Kích thước text: {processed_size:,} bytes ({len(cleaned_content):,} ký tự)")
print(f" - Số dòng: {len(cleaned_content.split(chr(10)))}")
return True
except Exception as e:
print(f"Lỗi khi xử lý DOCX {input_path}: {e}")
import traceback
traceback.print_exc()
return False
def main():
"""Hàm chính"""
# Tạo thư mục processed nếu chưa có
os.makedirs(PROCESSED_DIR, exist_ok=True)
# Kiểm tra thư mục raw
if not os.path.exists(RAW_DIR):
print(f"Thư mục {RAW_DIR} không tồn tại!")
print("Vui lòng tạo thư mục và đặt file dữ liệu vào đó.")
return
# Đếm số file đã xử lý
processed_count = 0
# Xử lý file .txt và .md
for ext in SUPPORTED_EXTENSIONS:
pattern = os.path.join(RAW_DIR, f"**/*{ext}")
for file_path in glob.glob(pattern, recursive=True):
if process_text_file(file_path, PROCESSED_DIR):
processed_count += 1
# Xử lý file .pdf
pdf_pattern = os.path.join(RAW_DIR, "**/*.pdf")
for file_path in glob.glob(pdf_pattern, recursive=True):
if process_pdf_file(file_path, PROCESSED_DIR):
processed_count += 1
# Xử lý file .docx
docx_pattern = os.path.join(RAW_DIR, "**/*.docx")
for file_path in glob.glob(docx_pattern, recursive=True):
if process_docx_file(file_path, PROCESSED_DIR):
processed_count += 1
print(f"\nHoàn thành! Đã xử lý {processed_count} file.")
print(f"Dữ liệu đã xử lý được lưu tại: {PROCESSED_DIR}/")
if __name__ == "__main__":
main()
|