|
|
|
|
|
|
|
|
|
|
|
import os |
|
|
import re |
|
|
|
|
|
def clean_line(line): |
|
|
result = [] |
|
|
in_brackets = False |
|
|
|
|
|
for char in line: |
|
|
if char == '(': |
|
|
|
|
|
in_brackets = True |
|
|
elif char == ')': |
|
|
|
|
|
in_brackets = False |
|
|
elif not in_brackets: |
|
|
|
|
|
result.append(char) |
|
|
|
|
|
|
|
|
return ''.join(result) |
|
|
|
|
|
|
|
|
def process_files(folder_path): |
|
|
""" |
|
|
遍历指定文件夹中的所有文件,逐行清洗包含括号的文本,并将结果写回原文件。 |
|
|
""" |
|
|
|
|
|
if not os.path.exists(folder_path): |
|
|
print(f"文件夹 {folder_path} 不存在!") |
|
|
return |
|
|
|
|
|
|
|
|
for file_name in os.listdir(folder_path): |
|
|
file_path = os.path.join(folder_path, file_name) |
|
|
|
|
|
|
|
|
if os.path.isfile(file_path): |
|
|
try: |
|
|
|
|
|
temp_file_path = file_path + ".tmp" |
|
|
with open(file_path, 'r', encoding='utf-8') as infile, open(temp_file_path, 'w', encoding='utf-8') as outfile: |
|
|
|
|
|
for line in infile: |
|
|
|
|
|
cleaned_line = clean_line(line) |
|
|
|
|
|
outfile.write(cleaned_line) |
|
|
|
|
|
|
|
|
os.replace(temp_file_path, file_path) |
|
|
print(f"已清洗并保存到: {file_name}") |
|
|
|
|
|
except Exception as e: |
|
|
print(f"处理文件 {file_name} 时出错: {e}") |
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
|
|
transcript_folder = "./transcript" |
|
|
|
|
|
|
|
|
process_files(transcript_folder) |