0xZohar's picture
Add code/cube3d/render/ldr_freq.py
4fcfffd verified
import os
import re
from collections import defaultdict
# 输入主文件夹路径,包含多个子文件夹
main_folder = "/public/home/wangshuo/gap/assembly/data/car_1k/ldr" # 替换为你的主文件夹路径
output_file = "part_count_with_files.txt" # 输出统计结果文件(可选)
# 统计零件的种类、频率和它们出现在多少个文件中的统计
part_count = defaultdict(int) # 统计零件出现的次数
part_file_count = defaultdict(set) # 统计零件出现在多少个不同的文件中
total_valid_lines = 0 # 统计有效的行数
# 遍历主文件夹中的所有子文件夹
for subdir in os.listdir(main_folder):
subdir_path = os.path.join(main_folder, subdir)
if os.path.isdir(subdir_path):
# 假设每个子文件夹中都有一个 LDR 文件
ldr_files = [f for f in os.listdir(subdir_path) if f.endswith('.ldr')]
for ldr_file in ldr_files:
ldr_path = os.path.join(subdir_path, ldr_file)
# 打开并读取每个 LDR 文件
with open(ldr_path, "r") as file:
for line in file:
# 只统计以 '1' 开头的行,代表零件
if line.startswith("1"):
total_valid_lines += 1 # 有效行数加 1
columns = line.split()
if len(columns) >= 15:
# 零件名称从第15列开始
part_name = " ".join(columns[14:]) # 合并第15列及后面的列
# 统计零件出现的次数
part_count[part_name] += 1
# 统计零件出现在多少个不同的 LDR 文件中
part_file_count[part_name].add(ldr_file)
# 输出零件种类、使用频率和出现在多少个文件中的统计
with open(output_file, "w") as f:
f.write("零件名称, 使用频率, 出现的 LDR 文件数\n")
for part_name, count in sorted(part_count.items(), key=lambda x: x[1], reverse=True):
file_count = len(part_file_count[part_name]) # 获取该零件出现在多少个不同文件
f.write(f"{part_name}, {count}, {file_count}\n")
# 输出统计信息
print(f"有效行数:{total_valid_lines}")
print(f"统计完成,结果已保存到 {output_file}")