deepseek: 切分類和長函數到同名文件中

import re
import sys
import os
import ast
from tokenize import generate_tokens, COMMENT, STRING, NL, INDENT, DEDENT
import iodef extract_entities(filename):"""提取類和函數到單獨文件"""with open(filename, 'r', encoding='utf-8') as f:content = f.read()# 計算總行數total_lines = content.count('\n') + 1long_function_threshold = max(80, total_lines // 12)# 初始化結果entities = []current_pos = 0# 嘗試使用AST解析獲取更準確的位置信息try:tree = ast.parse(content)ast_entities = []for node in tree.body:if isinstance(node, ast.ClassDef):start_line = node.linenoend_line = node.end_linenoast_entities.append(('class', node.name, start_line, end_line))elif isinstance(node, ast.FunctionDef):start_line = node.linenoend_line = node.end_linenoast_entities.append(('function', node.name, start_line, end_line))# 使用AST信息輔助提取lines = content.split('\n')for e_type, name, start_line, end_line in ast_entities:start_index = sum(len(line) + 1 for line in lines[:start_line-1])end_index = sum(len(line) + 1 for line in lines[:end_line]) - 1# 對于函數,檢查是否為長函數if e_type == 'function':func_lines = end_line - start_line + 1if func_lines > long_function_threshold:func_content = content[start_index:end_index]entities.append(('function', name, start_index, end_index, func_content))# 類總是提取elif e_type == 'class':class_content = content[start_index:end_index]entities.append(('class', name, start_index, end_index, class_content))except SyntaxError:# 如果AST解析失敗,使用基于縮進的方法return extract_entities_with_indent(content, total_lines, long_function_threshold)return entities, content, total_linesdef extract_entities_with_indent(content, total_lines, long_function_threshold):"""當AST解析失敗時使用基于縮進的方法"""entities = []current_pos = 0# 類定義正則(支持裝飾器和繼承)class_pattern = re.compile(r'^([ \t]*)@?.*?\b(class|struct)\s+(\w+)\s*[\(:]?[^{:]*[:{]?', re.MULTILINE)# 函數定義正則(支持裝飾器和類型注解)func_pattern = re.compile(r'^([ \t]*)@?.*?\b(def)\s+(\w+)\s*\([^{:]*\)\s*[^{:]*[:{]?', re.MULTILINE)# 提取類for match in class_pattern.finditer(content):indent = match.group(1)class_name = match.group(3)start_index = match.start()# 找到類體的結束位置end_index = find_block_end(content, start_index, indent)if end_index == -1:continueclass_content = content[start_index:end_index]entities.append(('class', class_name, start_index, end_index, class_content))current_pos = end_index# 提取函數(只提取頂級函數,忽略類內方法)for match in func_pattern.finditer(content):func_name = match.group(3)start_index = match.start()indent = match.group(1)# 跳過類內的方法if any(start_index > c_start and start_index < c_end for (t, _, c_start, c_end, _) in entities if t == 'class'):continue# 找到函數體的結束位置end_index = find_block_end(content, start_index, indent)if end_index == -1:continuefunc_content = content[start_index:end_index]func_lines = func_content.count('\n') + 1# 檢查是否為長函數if func_lines > long_function_threshold:entities.append(('function', func_name, start_index, end_index, func_content))current_pos = end_index# 按起始位置排序entities.sort(key=lambda x: x[2])return entities, content, total_linesdef find_block_end(content, start_index, base_indent):"""找到代碼塊的結束位置"""base_indent_level = len(base_indent) if base_indent else 0current_index = start_indexstack = []in_string = Falsestring_char = Nonewhile current_index < len(content):char = content[current_index]# 處理字符串字面量if not in_string and char in ('"', "'"):in_string = Truestring_char = charelif in_string and char == string_char:# 檢查是否是轉義的引號if content[current_index-1] == '\\':# 檢查轉義字符本身是否被轉義backslash_count = 0i = current_index - 1while i >= 0 and content[i] == '\\':backslash_count += 1i -= 1if backslash_count % 2 == 0:  # 偶數個反斜杠,引號未被轉義in_string = Falsestring_char = Noneelse:in_string = Falsestring_char = Noneif in_string:current_index += 1continue# 處理括號if char in '([{':stack.append(char)elif char in ')]}':if not stack:return -1  # 不匹配的括號last_open = stack.pop()if (last_open == '(' and char != ')') or \(last_open == '[' and char != ']') or \(last_open == '{' and char != '}'):return -1  # 括號不匹配# 檢查代碼塊結束if char == '\n':next_line_start = current_index + 1if next_line_start >= len(content):return next_line_start  # 文件結束# 檢查下一行的縮進級別next_line_end = content.find('\n', next_line_start)if next_line_end == -1:next_line_end = len(content)next_line = content[next_line_start:next_line_end]indent_level = len(next_line) - len(next_line.lstrip())# 如果縮進小于基礎縮進且沒有未閉合的括號,則塊結束if indent_level <= base_indent_level and not stack:# 確保不是空行或注釋stripped_line = next_line.strip()if stripped_line and not stripped_line.startswith('#'):return next_line_startcurrent_index += 1return len(content)  # 到達文件末尾def write_entities(entities, content, filename):"""將實體寫入文件并生成剩余內容"""# 創建輸出目錄base_name = os.path.splitext(os.path.basename(filename))[0]output_dir = f"{base_name}_split"os.makedirs(output_dir, exist_ok=True)# 提取覆蓋范圍covered_ranges = []for entity in entities:e_type, e_name, start, end, e_content = entity# 確保每個實體都寫入單獨的文件output_path = os.path.join(output_dir, f"{e_name}.py")with open(output_path, 'w', encoding='utf-8') as f:f.write(e_content)covered_ranges.append((start, end))# 生成剩余內容covered_ranges.sort(key=lambda x: x[0])remaining_parts = []last_pos = 0for start, end in covered_ranges:remaining_parts.append(content[last_pos:start])last_pos = endremaining_parts.append(content[last_pos:])remaining_content = ''.join(remaining_parts)# 寫入剩余文件left_path = os.path.join(output_dir, "left.py")with open(left_path, 'w', encoding='utf-8') as f:f.write(remaining_content)return output_dirdef main():if len(sys.argv) != 2:print("Usage: python split_code.py <source_file.py>")sys.exit(1)filename = sys.argv[1]if not os.path.isfile(filename):print(f"Error: File not found - {filename}")sys.exit(1)try:entities, content, total_lines = extract_entities(filename)output_dir = write_entities(entities, content, filename)class_count = sum(1 for e in entities if e[0] == 'class')func_count = sum(1 for e in entities if e[0] == 'function')print(f"Processed {filename}:")print(f"- Total lines: {total_lines}")print(f"- Long function threshold: {max(80, total_lines//12)} lines")print(f"- Extracted: {class_count} classes, {func_count} long functions")print(f"- Output directory: {output_dir}")print(f"- Remaining code in: {os.path.join(output_dir, 'left.py')}")except Exception as e:print(f"Error processing file: {str(e)}")import tracebacktraceback.print_exc()sys.exit(1)if __name__ == "__main__":main()

需求:?

寫一個python腳本,閱讀python源代碼,i, 把源文件中各個class 切分到文件中,文件名是類名,ii,長函數(代碼行超過本文件長度1/12, 或者超過80行,兩個條件滿足一個即可)切分到文件中,文件名是函數名。 iii,剩余部分放在left.py文件中,謝謝

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/91389.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/91389.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/91389.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

新型融合肽遞送外泌體修飾可注射溫敏水凝膠用于骨再生

溫敏水凝膠因能模擬細胞外基質微環境&#xff0c;且具有原位注射性和形態適應性&#xff0c;在骨組織工程中應用廣泛。小腸黏膜下層&#xff08;SIS&#xff09;作為天然細胞外基質來源&#xff0c;富含 I 型和 III 型膠原蛋白及多種生物活性因子&#xff0c;其制備的水凝膠在組…

SPI接口的4種模式(根據時鐘極性和時鐘相位)

SPI&#xff08;Serial Peripheral Interface&#xff09; 接口根據時鐘極性&#xff08;CPOL&#xff09;和時鐘相位&#xff08;CPHA&#xff09;的不同組合&#xff0c;共有 4種工作模式。這些模式決定了數據采樣和傳輸的時序關系&#xff0c;是SPI通信中必須正確配置的關鍵…

Java:高頻面試知識分享2

HashSet 和 TreeSet 的區別&#xff1f;底層實現&#xff1a;HashSet 基于 HashMap 實現&#xff0c;使用哈希表存儲元素&#xff1b;TreeSet 基于 TreeMap&#xff0c;底層為紅黑樹。元素順序&#xff1a;HashSet 無序&#xff1b;TreeSet 會根據元素的自然順序或傳入的 Compa…

C語言習題講解-第九講- 常見錯誤分類等

C語言習題講解-第九講- 常見錯誤分類等1. C程序常見的錯誤分類不包含&#xff1a;&#xff08; &#xff09;2. 根據下面遞歸函數&#xff1a;調用函數 Fun(2) &#xff0c;返回值是多少&#xff08; &#xff09;3. 關于遞歸的描述錯誤的是&#xff1a;&#xff08; &#x…

A?算法(A-star algorithm)一種在路徑規劃和圖搜索中廣泛使用的啟發式搜索算法

A?A*A?算法&#xff08;A-star algorithm&#xff09;是一種在路徑規劃和圖搜索中廣泛使用的啟發式搜索算法&#xff0c;它結合了Dijkstra算法的廣度優先搜索思想和啟發式算法的效率優勢&#xff0c;能夠高效地找到從起點到終點的最短路徑。 1. 基本原理 A*算法的核心是通過估…

UniappDay06

1.填寫訂單-渲染基本信息 靜態結構&#xff08;分包&#xff09;封裝請求API import { http } from /utils/http import { OrderPreResult } from /types/orderexport const getmemberOrderPreAPI () > {return http<OrderPreResult>({method: GET,url: /member/orde…

論文略讀:GINGER: Grounded Information Nugget-Based Generation of Responses

SIGIR 2025用戶日益依賴對話助手&#xff08;如 ChatGPT&#xff09;來滿足多種信息需求&#xff0c;這些需求包括開放式問題、需要推理的間接回答&#xff0c;以及答案分布在多個段落中的復雜查詢RAG試圖通過在生成過程中引入檢索到的信息來解決這些問題但如何確保回應的透明性…

從內部保護你的網絡

想象一下&#xff0c;你是一家高端俱樂部的老板&#xff0c;商務貴賓們聚集在這里分享信息、放松身心。然后假設你雇傭了最頂尖的安保人員——“保鏢”——站在門口&#xff0c;確保你準確掌握所有進出的人員&#xff0c;并確保所有人的安全。不妨想象一下丹尼爾克雷格和杜安約…

Redis 中 ZipList 的級聯更新問題

ZipList 的結構ZipList 是 Redis 中用于實現 ZSet 的壓縮數據結構&#xff0c;其元素采用連續存儲方式&#xff0c;具有很高的內存緊湊性。ZipList 結構組成如下&#xff1a;zlbytes&#xff1a;4字節&#xff0c;記錄整個ziplist的字節數zltail&#xff1a;4字節&#xff0c;記…

【蒼穹外賣項目】Day05

&#x1f4d8;博客主頁&#xff1a;程序員葵安 &#x1faf6;感謝大家點贊&#x1f44d;&#x1f3fb;收藏?評論?&#x1f3fb; 一、Redis入門 Redis簡介 Redis是一個基于內存的 key-value 結構數據庫 基于內存存儲&#xff0c;讀寫性能高適合存儲熱點數據&#xff08;熱…

語音識別dolphin 學習筆記

目錄 Dolphin簡介 Dolphin 中共有 4 個模型&#xff0c;其中 2 個現在可用。 使用demo Dolphin簡介 Dolphin 是由 Dataocean AI 和清華大學合作開發的多語言、多任務語音識別模型。它支持東亞、南亞、東南亞和中東的 40 種東方語言&#xff0c;同時支持 22 種漢語方言。該模…

視頻生成中如何選擇GPU或NPU?

在視頻生成中選擇GPU還是NPU&#xff0c;核心是根據場景需求、技術約束和成本目標來匹配兩者的特性。以下是具體的決策框架和場景化建議&#xff1a; 核心決策依據&#xff1a;先明確你的“視頻生成需求” 選擇前需回答3個關鍵問題&#xff1a; 生成目標&#xff1a;視頻分辨率…

從豆瓣小組到深度洞察:一個基于Python的輿情分析爬蟲實踐

文章目錄 從豆瓣小組到深度洞察:一個基于Python的輿情分析爬蟲實踐 摘要 1. 背景 2. 需求分析 3. 技術選型與實現 3.1 總體架構 3.2 核心代碼解析 4. 難點分析與解決方案 5. 總結與展望 對爬蟲、逆向感興趣的同學可以查看文章,一對一小班教學:https://blog.csdn.net/weixin_…

RustDesk 使用教程

說明&#xff1a; 使用RustDesk 需要在不同的電腦安裝對應系統型號的客戶端&#xff0c;然后再去云服務器安裝一個服務端即可。 1、到網站下載客戶端&#xff1a;https://rustdesk.com/zh-cn/ 兩臺電腦安裝客戶端。 2、在云服務器安裝服務端 1&#xff09;官網教程&#xff1a;…

【C語言網絡編程基礎】TCP 服務器詳解

在網絡通信中&#xff0c;TCP&#xff08;Transmission Control Protocol&#xff0c;傳輸控制協議&#xff09;是一種可靠、面向連接的協議。一個 TCP 服務器正是基于這種協議&#xff0c;為客戶端提供穩定的網絡服務。本文將詳細介紹 TCP 服務器的基本原理和工作流程。 一、什…

一篇就夠!Windows上Docker Desktop安裝 + 漢化完整指南(包含解決wsl更新失敗方案)

前言 在現代軟件開發和人工智能應用中&#xff0c;環境的穩定性和可移植性至關重要。Docker 作為一種輕量級的容器化技術&#xff0c;為開發者提供一致的運行環境&#xff0c;使得軟件可以在不同平臺上無縫運行&#xff0c;極大地提升了開發和部署的效率。無論是本地開發、測試…

設計模式(二十四)行為型:訪問者模式詳解

設計模式&#xff08;二十四&#xff09;行為型&#xff1a;訪問者模式詳解訪問者模式&#xff08;Visitor Pattern&#xff09;是 GoF 23 種設計模式中最具爭議性但也最強大的行為型模式之一&#xff0c;其核心價值在于將作用于某種數據結構中的各元素的操作分離出來&#xff…

USRP X440 和USRP X410 直接RF采樣架構的優勢

USRP X440 和USRP X410 直接RF采樣架構的優勢概述什么是直接RF采樣&#xff1f;如何實現直接采樣&#xff1f;什么情況下應考慮使用直接RF采樣架構&#xff1f;概述 轉換器技術每年都在發展。主要半導體公司的模數轉換器(ADC)和數模轉換器(DAC)的采樣速率比十年前的產品快了好…

P4568 [JLOI2011] 飛行路線

P4568 [JLOI2011] 飛行路線 題目描述 Alice 和 Bob 現在要乘飛機旅行&#xff0c;他們選擇了一家相對便宜的航空公司。該航空公司一共在 nnn 個城市設有業務&#xff0c;設這些城市分別標記為 000 到 n?1n-1n?1&#xff0c;一共有 mmm 種航線&#xff0c;每種航線連接兩個城市…

MySQL 中的聚簇索引和非聚簇索引的區別

MySQL 中的聚簇索引和非聚簇索引的區別 總結性回答 聚簇索引和非聚簇索引的主要區別在于索引的組織方式和數據存儲位置。聚簇索引決定了表中數據的物理存儲順序&#xff0c;一個表只能有一個聚簇索引&#xff1b;而非聚簇索引是獨立于數據存儲的額外結構&#xff0c;一個表可以…