(input_file, output_file, strong_clean_flag = False)
| 35 | |
| 36 | |
| 37 | def remove_text_in_brackets(input_file, output_file, strong_clean_flag = False): |
| 38 | def process(line): |
| 39 | """ |
| 40 | 删除字符串中括号及其中的内容。 |
| 41 | 包括括号 () 和中文括号()。 |
| 42 | :param line: 原始字符串 |
| 43 | :return: 删除括号内容后的字符串 |
| 44 | """ |
| 45 | # 使用正则表达式匹配括号及其中的内容 |
| 46 | # 匹配圆括号 () 或中文括号(),以及其中的内容 |
| 47 | return re.sub(r"[\(\(][^\)\)]*[\)\)]", "", line) |
| 48 | |
| 49 | def remove_non_alpha(string): |
| 50 | # 使用正则表达式删除首尾非字母字符 |
| 51 | cleaned_string = re.sub(r'^[^a-zA-Z]+|[^a-zA-Z]+$', '', string) |
| 52 | return cleaned_string |
| 53 | |
| 54 | # 确保输入文件存在 |
| 55 | if not os.path.exists(input_file): |
| 56 | print(f"输入文件 {input_file} 不存在!") |
| 57 | return |
| 58 | |
| 59 | try: |
| 60 | # 打开输入文件和输出文件 |
| 61 | with open(input_file, "r", encoding="utf-8") as infile, open( |
| 62 | output_file, "w", encoding="utf-8" |
| 63 | ) as outfile: |
| 64 | cnt = 0 |
| 65 | # 按行读取输入文件 |
| 66 | for line in infile: |
| 67 | cnt += 1 |
| 68 | # 删除当前行中括号及其中的内容 |
| 69 | line_wo_bracket = process(line) |
| 70 | if strong_clean_flag == True: |
| 71 | # 删除前后的数字和符号 |
| 72 | processed_line = remove_non_alpha(line_wo_bracket) |
| 73 | # 写入到输出文件 |
| 74 | outfile.write(processed_line + "\n") |
| 75 | if cnt % 10000 == 0: |
| 76 | print(f"处理进度: {cnt}") |
| 77 | |
| 78 | print(f"处理完成!结果已保存到 {output_file}") |
| 79 | except Exception as e: |
| 80 | print(f"处理文件时出现错误:{e}") |
| 81 | |
| 82 | |
| 83 | def sort_large_file( |
nothing calls this directly
no test coverage detected