基於Python開發一個智能編程學習助手,專注於代碼分析和實時指導。

核心功能設計

# ai_coding_tutor.py
import ast
import inspect
from typing import Dict, List, Optional
from dataclasses import dataclass
from pathlib import Path

@dataclass
class CodeAnalysis:
    complexity: int
    issues: List[str]
    suggestions: List[str]
    best_practices: List[str]

class AICodingTutor:
    def __init__(self):
        self.code_patterns = self._load_code_patterns()
        self.common_mistakes = self._load_common_mistakes()
    
    def analyze_code(self, code: str, language: str = "python") -> CodeAnalysis:
        """分析代碼並提供反饋"""
        if language == "python":
            return self._analyze_python_code(code)
        else:
            return self._analyze_general_code(code)
    
    def _analyze_python_code(self, code: str) -> CodeAnalysis:
        """分析Python代碼"""
        issues = []
        suggestions = []
        best_practices = []
        
        try:
            tree = ast.parse(code)
            
            # 分析代碼複雜度
            complexity = self._calculate_complexity(tree)
            
            # 檢查常見問題
            issues.extend(self._check_code_issues(tree))
            
            # 提供改進建議
            suggestions.extend(self._generate_suggestions(tree))
            
            # 推薦最佳實踐
            best_practices.extend(self._suggest_best_practices(tree))
            
        except SyntaxError as e:
            issues.append(f"語法錯誤: {e}")
        
        return CodeAnalysis(
            complexity=complexity,
            issues=issues,
            suggestions=suggestions,
            best_practices=best_practices
        )
    
    def real_time_feedback(self, code: str, cursor_position: int) -> Dict:
        """實時代碼反饋"""
        feedback = {
            "hints": [],
            "warnings": [],
            "completions": []
        }
        
        # 分析當前行
        lines = code.split('\n')
        current_line = self._get_current_line(lines, cursor_position)
        
        if self._detect_missing_colon(current_line):
            feedback["hints"].append("可能缺少冒號")
        
        if self._detect_unused_variable(current_line, code):
            feedback["warnings"].append("檢測到未使用變量")
        
        # 提供代碼補全建議
        feedback["completions"] = self._suggest_completions(current_line)
        
        return feedback

# 使用示例
tutor = AICodingTutor()

# 分析代碼
code_sample = """
def calculate_sum(numbers):
    total = 0
    for num in numbers:
        total = total + num
    return total
"""

analysis = tutor.analyze_code(code_sample)
print(f"代碼複雜度: {analysis.complexity}")
print("問題:", analysis.issues)
print("建議:", analysis.suggestions)

Web界面集成

# app.py
from flask import Flask, render_template, request, jsonify
import json

app = Flask(__name__)
tutor = AICodingTutor()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/analyze', methods=['POST'])
def analyze_code():
    code = request.json.get('code', '')
    language = request.json.get('language', 'python')
    
    analysis = tutor.analyze_code(code, language)
    
    return jsonify({
        'complexity': analysis.complexity,
        'issues': analysis.issues,
        'suggestions': analysis.suggestions,
        'best_practices': analysis.best_practices
    })

@app.route('/realtime-feedback', methods=['POST'])
def realtime_feedback():
    code = request.json.get('code', '')
    cursor_pos = request.json.get('cursor_position', 0)
    
    feedback = tutor.real_time_feedback(code, cursor_pos)
    
    return jsonify(feedback)

if __name__ == '__main__':
    app.run(debug=True)

簡單前端界面

<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>AI編程導師</title>
    <style>
        .container { display: flex; height: 100vh; }
        .editor { flex: 1; padding: 20px; }
        .feedback { flex: 1; padding: 20px; background: #f5f5f5; }
        textarea { width: 100%; height: 70%; font-family: monospace; }
    </style>
</head>
<body>
    <div class="container">
        <div class="editor">
            <h3>代碼編輯器</h3>
            <textarea id="codeEditor" placeholder="輸入你的代碼..."></textarea>
            <button onclick="analyzeCode()">分析代碼</button>
        </div>
        <div class="feedback">
            <h3>AI反饋</h3>
            <div id="feedbackArea"></div>
        </div>
    </div>

    <script>
        async function analyzeCode() {
            const code = document.getElementById('codeEditor').value;
            const response = await fetch('/analyze', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({code: code})
            });
            const result = await response.json();
            displayFeedback(result);
        }

        function displayFeedback(analysis) {
            let html = `<p><strong>複雜度:</strong> ${analysis.complexity}</p>`;
            html += `<p><strong>問題:</strong> ${analysis.issues.join(', ')}</p>`;
            html += `<p><strong>建議:</strong> ${analysis.suggestions.join(', ')}</p>`;
            document.getElementById('feedbackArea').innerHTML = html;
        }
    </script>
</body>
</html>

這個AI編程導師系統提供:

  • 實時代碼分析
  • 智能錯誤檢測
  • 代碼改進建議
  • 最佳實踐指導
  • 簡單的Web界面

適合編程學習者使用,幫助提高代碼質量。