IntuitionX_agent/tools/fullwidth_to_halfwidth_converter.py
2026-01-01 17:48:45 +08:00

155 lines
4.1 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
全角字符转半角字符工具脚本
用于将Python文件中的全角括号、逗号等字符转换为半角
"""
import sys
from pathlib import Path
def fullwidth_to_halfwidth(text: str) -> str:
"""
将文本中的全角字符转换为半角字符
Args:
text: 输入文本
Returns:
转换后的文本
"""
# 定义全角到半角的映射
fullwidth_chars = {
"": "(",
"": ")",
"": ",",
"": ";",
"": ":",
"": ".",
"": "?",
"": "!",
"": '"',
"": "'",
"": "[",
"": "]",
"": "{",
"": "}",
" ": " ", # 全角空格
}
# 处理每个字符
result = []
for char in text:
result.append(fullwidth_chars.get(char, char))
return "".join(result)
def convert_file(file_path: Path) -> bool:
"""
转换单个文件中的全角字符
Args:
file_path: 文件路径
Returns:
如果文件被修改则返回True否则返回False
"""
if not file_path.exists():
print(f"文件不存在: {file_path}")
return False
if file_path.suffix != ".py":
print(f"跳过非Python文件: {file_path}")
return False
# 忽略自身文件,防止无限循环
if file_path.name == "fullwidth_to_halfwidth_converter.py":
print(f"跳过自身文件: {file_path}")
return False
# 读取原始内容
with open(file_path, encoding="utf-8") as f:
original_content = f.read()
# 转换全角字符
converted_content = fullwidth_to_halfwidth(original_content)
# 如果内容发生了变化,则写回文件
if original_content != converted_content:
print(f"转换文件: {file_path}")
with open(file_path, "w", encoding="utf-8") as f:
f.write(converted_content)
return True
return False
def convert_files_in_directory(directory: Path, pattern: str = "*.py") -> int:
"""
转换目录下所有匹配模式的文件
Args:
directory: 目录路径
pattern: 文件匹配模式
Returns:
修改的文件数量
"""
if not directory.exists():
print(f"目录不存在: {directory}")
return 0
python_files = list(directory.rglob(pattern))
modified_count = 0
for file_path in python_files:
if convert_file(file_path):
modified_count += 1
return modified_count
def main():
"""主函数,处理命令行参数"""
if len(sys.argv) < 2:
print("使用示例:")
print(" 处理单个文件: python fullwidth_to_halfwidth_converter.py ./main.py")
print(" 处理多个文件: python fullwidth_to_halfwidth_converter.py "
"file1.py file2.py file3.py")
print(" 处理整个目录: python fullwidth_to_halfwidth_converter.py ./src")
sys.exit(1)
modified_count = 0
total_files = 0
# 处理所有传入的路径参数(支持多文件和目录)
for path_arg in sys.argv[1:]:
target_path = Path(path_arg)
if target_path.is_file():
# 处理单个文件
total_files += 1
if convert_file(target_path):
modified_count += 1
elif target_path.is_dir():
# 处理目录下的所有Python文件
pattern = "*.py"
dir_modified = convert_files_in_directory(target_path, pattern)
modified_count += dir_modified
# 统计目录中的文件数
total_files += len(list(target_path.rglob(pattern)))
else:
print(f"⚠️ 路径不存在: {target_path}")
# 输出处理结果
if total_files > 0:
print(f"✅ 处理完成: 共检查 {total_files} 个文件,转换了 {modified_count} 个文件")
else:
print("⚠️ 没有找到需要处理的文件")
# 如果有文件被修改返回非零状态码通知pre-commit需要重新暂存
sys.exit(1 if modified_count > 0 else 0)
if __name__ == "__main__":
main()