"""
#該程序用于清洗chatGPT結(jié)果
#運(yùn)行時(shí)檢查同目錄的所有.txt文檔,運(yùn)行時(shí)需要顯示替換進(jìn)度,還要顯示當(dāng)前正在處理哪個(gè)文件。
#步驟一:如果文檔中出現(xiàn)后面引號(hào)中包含的內(nèi)容,全部替換為空白,“}”、“$”、“\”、“text”、“bf”、“{”、"#",替換后的文件不改名覆蓋原文件;
#執(zhí)行完步驟一后執(zhí)行步驟二:如果文檔中存在連續(xù)≥2行以上的空白行就把≥2行以上的空白行替換為單行空白行,替換后的文件不改名覆蓋原文件;
#執(zhí)行完步驟二后執(zhí)行步驟三:如果內(nèi)容中出現(xiàn)"標(biāo)題:"就把"標(biāo)題:"這三個(gè)字符還有他前面的內(nèi)容都刪除,“標(biāo)題:”前面的內(nèi)容刪除,“標(biāo)題:”本身也不要保留,修改后的文件不改名覆蓋原文件
"""
import os
import re
from tqdm import tqdm
def step_one_replace(directory):
# 獲取當(dāng)前目錄下的所有.txt文件
txt_files = [f for f in os.listdir(directory) if f.endswith('.txt')]
# 遍歷每個(gè).txt文件
for txt_file in tqdm(txt_files, desc="步驟1[替換特殊字符]進(jìn)度"):
print(f"正在處理文件: {txt_file}")
file_path = os.path.join(directory, txt_file)
# 讀取文件內(nèi)容
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# 替換規(guī)則1
content = re.sub(r'[}$\\textbf{#]', '', content)
# 寫(xiě)入替換后的內(nèi)容到同一文件中
with open(file_path, 'w', encoding='utf-8') as file:
file.write(content)
print("步驟1[替換特殊字符]完成。")
def step_two_replace(directory):
# 獲取當(dāng)前目錄下的所有.txt文件
txt_files = [f for f in os.listdir(directory) if f.endswith('.txt')]
# 遍歷每個(gè).txt文件
for txt_file in tqdm(txt_files, desc="步驟2[替換多行空白行]進(jìn)度"):
print(f"正在處理文件: {txt_file}")
file_path = os.path.join(directory, txt_file)
# 讀取文件內(nèi)容
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# 替換規(guī)則2
content = re.sub(r'\n\s*\n\s*\n+', '\n\n', content)
# 寫(xiě)入替換后的內(nèi)容到同一文件中
with open(file_path, 'w', encoding='utf-8') as file:
file.write(content)
print("步驟2[替換空白行]完成。")
def step_three_replace(directory):
# 獲取當(dāng)前目錄下的所有.txt文件
txt_files = [f for f in os.listdir(directory) if f.endswith('.txt')]
# 遍歷每個(gè).txt文件
for txt_file in tqdm(txt_files, desc="步驟3[刪除標(biāo)題前面內(nèi)容]進(jìn)度"):
print(f"正在處理文件: {txt_file}")
file_path = os.path.join(directory, txt_file)
# 讀取文件內(nèi)容
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# 替換規(guī)則3
content = re.sub(r'.*?標(biāo)題[::](.*?)(\n|$)', r'\1\2', content)
# 寫(xiě)入替換后的內(nèi)容到同一文件中
with open(file_path, 'w', encoding='utf-8') as file:
file.write(content)
print("步驟3[刪除標(biāo)題前面內(nèi)容]。")
# 運(yùn)行步驟一替換函數(shù)
step_one_replace(os.getcwd()) # 使用當(dāng)前目錄作為起點(diǎn)
# 運(yùn)行步驟二替換函數(shù)
step_two_replace(os.getcwd()) # 使用當(dāng)前目錄作為起點(diǎn)
# 運(yùn)行步驟三替換函數(shù)
step_three_replace(os.getcwd()) # 使用當(dāng)前目錄作為起點(diǎn)