文件预览

parenting_assessment.py

查看 parents-homework 技能包中的文件内容。

文件内容

scripts/parenting_assessment.py

#!/usr/bin/env python3
"""
父母教养风格评估问卷系统
Parenting Style Assessment Questionnaire System

基于心理学研究开发的自我评估工具,帮助父母了解自己的教养风格。
"""

import json
import os
from datetime import datetime
from typing import Dict, List, Optional

# 评估问卷题目
QUESTIONNAIRE = {
    "authoritarian": {
        "name": "专制型",
        "description": "高要求、低回应型教养风格",
        "questions": [
            {"id": "a1", "text": "我认为孩子应该完全服从父母的决定"},
            {"id": "a2", "text": "我不解释为什么制定规则,孩子遵守就是了"},
            {"id": "a3", "text": "当孩子不听话时,我会用惩罚而不是沟通"},
            {"id": "a4", "text": "我认为严格管教是爱孩子的表现"},
            {"id": "a5", "text": "我不允许孩子质疑我的决定"},
        ]
    },
    "authoritative": {
        "name": "权威型",
        "description": "高要求、高回应型教养风格(最理想)",
        "questions": [
            {"id": "b1", "text": "我会解释制定规则的原因,并倾听孩子的想法"},
            {"id": "b2", "text": "我对孩子有明确的期望,但也会考虑他们的意见"},
            {"id": "b3", "text": "我会在坚定原则的同时,表达对孩子的关爱"},
            {"id": "b4", "text": "我会根据孩子的表现调整管教方式"},
            {"id": "b5", "text": "我鼓励孩子独立思考,同时设定清晰的界限"},
        ]
    },
    "permissive": {
        "name": "溺爱型",
        "description": "低要求、高回应型教养风格",
        "questions": [
            {"id": "c1", "text": "我尽量避免与孩子发生冲突"},
            {"id": "c2", "text": "我认为孩子高兴最重要,规则可以灵活"},
            {"id": "c3", "text": "我很少对孩子说"不"或设置限制"},
            {"id": "c4", "text": "我尽量满足孩子的所有要求"},
            {"id": "c5", "text": "我认为孩子会自己学会规矩"},
        ]
    },
    "neglectful": {
        "name": "忽视型",
        "description": "低要求、低回应型教养风格",
        "questions": [
            {"id": "d1", "text": "我经常忙于工作,没有时间陪伴孩子"},
            {"id": "d2", "text": "我不了解孩子在学校的情况"},
            {"id": "d3", "text": "我很少参与孩子的日常活动"},
            {"id": "d4", "text": "我对孩子的情绪不太关注"},
            {"id": "d5", "text": "我认为孩子应该自己管自己"},
        ]
    }
}

class ParentingAssessment:
    """父母教养风格评估类"""
    
    def __init__(self, data_dir: str = None):
        if data_dir is None:
            data_dir = os.path.join(os.path.dirname(__file__), '..', 'data')
        self.data_dir = os.path.abspath(data_dir)
        os.makedirs(self.data_dir, exist_ok=True)
        self.responses_file = os.path.join(self.data_dir, 'assessment_responses.json')
        
    def run_questionnaire(self) -> Dict:
        """运行问卷评估"""
        print("\n" + "="*50)
        print("父母教养风格评估问卷")
        print("="*50)
        print("\n请根据您的真实情况,选择最符合的选项(1-5分):")
        print("1 = 完全不符合  2 = 偶尔符合  3 = 有时符合  4 = 经常符合  5 = 完全符合\n")
        
        scores = {style: 0 for style in QUESTIONNAIRE.keys()}
        
        for style_key, style_data in QUESTIONNAIRE.items():
            print(f"\n【{style_data['name']}】- {style_data['description']}")
            
            for q in style_data['questions']:
                while True:
                    try:
                        score = int(input(f"  {q['text']}\n  分数(1-5): "))
                        if 1 <= score <= 5:
                            scores[style_key] += score
                            break
                        else:
                            print("  请输入1-5之间的数字")
                    except ValueError:
                        print("  请输入有效的数字")
        
        return scores
    
    def calculate_results(self, scores: Dict) -> Dict:
        """计算评估结果"""
        total = sum(scores.values())
        max_possible = len(QUESTIONNAIRE) * 5 * 5  # 4 styles * 5 questions * 5 max
        
        results = {}
        for style, score in scores.items():
            percentage = (score / 25) * 100  # 5 questions * 5 max
            results[style] = {
                "name": QUESTIONNAIRE[style]["name"],
                "score": score,
                "percentage": round(percentage, 1)
            }
        
        # 确定主要风格
        dominant_style = max(scores, key=scores.get)
        results["dominant_style"] = dominant_style
        results["dominant_name"] = QUESTIONNAIRE[dominant_style]["name"]
        results["timestamp"] = datetime.now().isoformat()
        
        return results
    
    def save_results(self, results: Dict, filename: str = None) -> str:
        """保存评估结果"""
        if filename is None:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"assessment_{timestamp}.json"
        
        filepath = os.path.join(self.data_dir, filename)
        
        # 加载历史数据
        history = []
        if os.path.exists(self.responses_file):
            with open(self.responses_file, 'r', encoding='utf-8') as f:
                history = json.load(f)
        
        history.append(results)
        
        with open(self.responses_file, 'w', encoding='utf-8') as f:
            json.dump(history, f, ensure_ascii=False, indent=2)
        
        return filepath
    
    def print_results(self, results: Dict):
        """打印评估结果"""
        print("\n" + "="*50)
        print("评估结果")
        print("="*50)
        
        print("\n各风格得分:")
        for style, data in results.items():
            if style in QUESTIONNAIRE:
                bar = "█" * int(data['percentage'] / 5)
                print(f"  {data['name']}: {data['score']}分 ({data['percentage']}%) {bar}")
        
        print(f"\n【主要风格】: {results['dominant_name']}")
        
        # 给出建议
        recommendations = {
            "authoritarian": "建议增加与孩子的沟通,解释规则的原因,尊重孩子的想法。",
            "authoritative": "继续保持!您正在采用最理想的教养方式。",
            "permissive": "建议适当设立明确的规则和界限,帮助孩子建立规则感。",
            "neglectful": "建议增加与孩子的互动时间,关注孩子的情感需求。"
        }
        
        print(f"\n【建议】: {recommendations[results['dominant_style']]}")
    
    def get_history(self) -> List[Dict]:
        """获取历史评估记录"""
        if os.path.exists(self.responses_file):
            with open(self.responses_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        return []
    
    def compare_progress(self) -> Dict:
        """比较进步情况"""
        history = self.get_history()
        if len(history) < 2:
            return {"message": "历史记录不足,需要至少2次评估才能比较"}
        
        latest = history[-1]
        previous = history[-2]
        
        comparison = {
            "latest_date": latest['timestamp'],
            "previous_date": previous['timestamp'],
            "changes": {}
        }
        
        for style in QUESTIONNAIRE.keys():
            if style in latest and style in previous:
                change = latest[style]['score'] - previous[style]['score']
                comparison['changes'][style] = {
                    "name": latest[style]['name'],
                    "change": change,
                    "direction": "↑" if change > 0 else ("↓" if change < 0 else "→")
                }
        
        return comparison


def main():
    """主函数"""
    assessor = ParentingAssessment()
    
    print("\n欢迎使用父母教养风格评估系统")
    print("本系统基于心理学研究,帮助您了解自己的教养风格\n")
    
    # 询问是否查看历史
    history = assessor.get_history()
    if history:
        print(f"发现 {len(history)} 条历史评估记录")
        compare = assessor.compare_progress()
        if "message" not in compare:
            print("\n与上次评估比较:")
            for style, data in compare['changes'].items():
                print(f"  {data['name']}: {data['direction']} ({data['change']:+d}分)")
    
    # 运行评估
    scores = assessor.run_questionnaire()
    results = assessor.calculate_results(scores)
    assessor.print_results(results)
    
    # 保存结果
    filepath = assessor.save_results(results)
    print(f"\n评估结果已保存至: {filepath}")
    
    return results


if __name__ == "__main__":
    main()