Spaces:
Paused
Paused
| import os | |
| import re | |
| from collections import defaultdict | |
| def count_dat_usage(folder_path): | |
| """ | |
| 统计文件夹中所有LDR文件里DAT文件的使用频率 | |
| 参数: | |
| folder_path: LDR文件所在的文件夹路径 | |
| 返回: | |
| 按使用频率排序的DAT文件字典列表 | |
| """ | |
| # 用于存储每个DAT文件的使用次数 | |
| dat_counts = defaultdict(int) | |
| # 正则表达式模式,用于匹配LDR文件中的DAT引用 | |
| # LDR格式中,零件引用通常类似: 1 0 0 0 1 0 0 0 1 0 part.dat | |
| dat_pattern = re.compile(r'\b(\w+\.dat)\b', re.IGNORECASE) | |
| # 遍历文件夹中的所有文件 | |
| for root, dirs, files in os.walk(folder_path): | |
| for file in files: | |
| # 只处理LDR文件 | |
| if file.lower().endswith('.ldr'): | |
| file_path = os.path.join(root, file) | |
| try: | |
| # 打开并读取LDR文件 | |
| with open(file_path, 'r', encoding='utf-8', errors='ignore') as f: | |
| line_number = 0 | |
| for line in f: | |
| line_number += 1 | |
| # 跳过注释行和空行(LDR中以0开头的通常是注释或元数据) | |
| stripped_line = line.strip() | |
| if not stripped_line or stripped_line.startswith('0 '): | |
| continue | |
| # 在有效行中查找DAT文件引用 | |
| matches = dat_pattern.findall(line) | |
| for dat_file in matches: | |
| # 统一转为小写,避免大小写导致的重复计数 | |
| dat_file_lower = dat_file.lower() | |
| dat_counts[dat_file_lower] += 1 | |
| except Exception as e: | |
| print(f"处理文件 {file_path} 时出错: {str(e)}") | |
| # 按使用频率从高到低排序 | |
| sorted_dats = sorted(dat_counts.items(), key=lambda x: x[1], reverse=True) | |
| return sorted_dats | |
| def main(): | |
| import sys | |
| # # 获取用户输入的文件夹路径 | |
| # if len(sys.argv) > 1: | |
| # folder_path = sys.argv[1] | |
| # else: | |
| # folder_path = input("请输入LDR文件所在的文件夹路径: ") | |
| folder_path = "/public/home/wangshuo/gap/assembly/data/car_1k/subset_self/ldr_l30_rotrans_expand_wom_flip" | |
| # 验证文件夹路径是否有效 | |
| if not os.path.isdir(folder_path): | |
| print(f"错误: {folder_path} 不是有效的文件夹路径") | |
| return | |
| print(f"正在统计 {folder_path} 中LDR文件的DAT使用频率...") | |
| dat_usage = count_dat_usage(folder_path) | |
| print("\nDAT文件使用频率统计结果(按使用次数排序):") | |
| print("==========================================") | |
| for i, (dat_file, count) in enumerate(dat_usage, 1): | |
| print(f"{i}. {dat_file}: {count} 次") | |
| # 也可以将结果保存到文件 | |
| output_file = "dat_usage统计结果.txt" | |
| with open(output_file, 'w', encoding='utf-8') as f: | |
| f.write("DAT文件使用频率统计结果(按使用次数排序):\n") | |
| f.write("==========================================\n") | |
| for i, (dat_file, count) in enumerate(dat_usage, 1): | |
| f.write(f"{i}. {dat_file}: {count} 次\n") | |
| print(f"\n统计结果已保存到 {output_file}") | |
| if __name__ == "__main__": | |
| main() | |