|
下面是一个与提供的 Bash 脚本等效的 Python 脚本。
- import os
- import re
- def process_tex_files():
- """
- Finds all .tex files in the current directory and its subdirectories,
- and replaces LaTeX inline and display math delimiters with standard
- dollar sign delimiters.
- """
- script_dir = os.getcwd()
-
- # Regex to find \(, \), \[, \]
- # We use re.escape to handle special characters in the search patterns
- # and then craft the replacement string.
- # The order of replacements matters if there are overlapping patterns,
- # but here \( and \) are distinct from \[ and \].
- replacements = [
- (re.compile(r'\\\('), '$'), # Replace \( with $
- (re.compile(r'\\\)'), '$'), # Replace \) with $
- (re.compile(r'\\\[', ), '$$'), # Replace \[ with $$
- (re.compile(r'\\\]'), '$$') # Replace \] with $$
- ]
- processed_count = 0
-
- for root, _, files in os.walk(script_dir):
- for file_name in files:
- if file_name.endswith(".tex"):
- file_path = os.path.join(root, file_name)
-
- try:
- with open(file_path, 'r', encoding='utf-8') as f:
- content = f.read()
- new_content = content
- for pattern, replacement in replacements:
- new_content = pattern.sub(replacement, new_content)
- if new_content != content: # Only write if changes were made
- temp_file_path = file_path + ".tmp"
- with open(temp_file_path, 'w', encoding='utf-8') as f_tmp:
- f_tmp.write(new_content)
-
- os.replace(temp_file_path, file_path) # Atomically replace the original file
- print(f"Processed {file_path}")
- processed_count += 1
- # else:
- # print(f"No changes needed for {file_path}")
- except Exception as e:
- print(f"Error processing {file_path}: {e}")
-
- print(f"All {processed_count} .tex files processed.")
- if __name__ == "__main__":
- process_tex_files()
Copy the Code 此脚本会查找当前目录及其子目录中的所有 .tex 文件,然后分别将 \\(、\\)、\\[ 和 \\] 替换为 \$ 和 \$\$。它通过写入临时文件并重命名来安全地处理文件。 |
|