|
| 1 | +import os |
| 2 | +import re |
| 3 | +import sys |
| 4 | +from collections import Counter |
| 5 | + |
| 6 | +import pandas as pd |
| 7 | + |
| 8 | + |
| 9 | +def extract_function_calls_with_count(csv_file_path): |
| 10 | + """ |
| 11 | + 从CSV文件的message列中提取函数调用名称及其出现次数 |
| 12 | +
|
| 13 | + 参数: |
| 14 | + csv_file_path (str): CSV文件路径 |
| 15 | +
|
| 16 | + 返回: |
| 17 | + list: 包含(函数名, 次数)的元组列表,按次数降序排列 |
| 18 | + """ |
| 19 | + try: |
| 20 | + # 检查文件是否存在 |
| 21 | + if not os.path.exists(csv_file_path): |
| 22 | + print(f"错误: 文件 {csv_file_path} 不存在") |
| 23 | + return [] |
| 24 | + |
| 25 | + # 读取CSV文件 |
| 26 | + df = pd.read_csv(csv_file_path) |
| 27 | + |
| 28 | + # 检查message列是否存在 |
| 29 | + if 'message' not in df.columns: |
| 30 | + print("错误: CSV文件中没有'message'列") |
| 31 | + return [] |
| 32 | + |
| 33 | + function_counter = Counter() |
| 34 | + |
| 35 | + # 正则表达式匹配函数调用模式 |
| 36 | + # 匹配类似 run_piloteye({...}) 这样的结构 |
| 37 | + pattern = r'(\w+)\s*\(\s*\{' |
| 38 | + |
| 39 | + for message in df['message']: |
| 40 | + if pd.isna(message): |
| 41 | + continue |
| 42 | + |
| 43 | + # 在message中查找匹配的函数调用 |
| 44 | + matches = re.findall(pattern, str(message)) |
| 45 | + function_counter.update(matches) |
| 46 | + |
| 47 | + # 按次数降序排序 |
| 48 | + sorted_functions = sorted( |
| 49 | + function_counter.items(), key=lambda x: x[1], reverse=True |
| 50 | + ) |
| 51 | + return sorted_functions |
| 52 | + |
| 53 | + except Exception as e: |
| 54 | + print(f"读取文件时出错: {e}") |
| 55 | + return [] |
| 56 | + |
| 57 | + |
| 58 | +def main(): |
| 59 | + """主函数,处理命令行参数""" |
| 60 | + # 检查是否提供了文件路径参数 |
| 61 | + if len(sys.argv) < 2: |
| 62 | + print('用法: python script.py <csv文件路径>') |
| 63 | + print('示例: python script.py /path/to/your/file.csv') |
| 64 | + sys.exit(1) |
| 65 | + |
| 66 | + # 获取第一个参数作为文件路径 |
| 67 | + csv_file_path = sys.argv[1] |
| 68 | + |
| 69 | + # 提取函数调用名称及次数 |
| 70 | + functions_with_count = extract_function_calls_with_count(csv_file_path) |
| 71 | + |
| 72 | + if functions_with_count: |
| 73 | + print('函数调用统计 (按次数降序排序):') |
| 74 | + print('-' * 40) |
| 75 | + for i, (func_name, count) in enumerate(functions_with_count, 1): |
| 76 | + print(f"{i:2d}. {func_name:<20} 出现次数: {count}") |
| 77 | + |
| 78 | + # 输出总计 |
| 79 | + total_calls = sum(count for _, count in functions_with_count) |
| 80 | + print('-' * 40) |
| 81 | + print(f"总计: {len(functions_with_count)} 个不同的函数, {total_calls} 次调用") |
| 82 | + else: |
| 83 | + print('未找到任何函数调用') |
| 84 | + |
| 85 | + |
| 86 | +if __name__ == '__main__': |
| 87 | + main() |
0 commit comments