-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror_lookup.py
More file actions
149 lines (124 loc) · 5 KB
/
Copy patherror_lookup.py
File metadata and controls
149 lines (124 loc) · 5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#!/usr/bin/env python3
"""
Python错误查询工具
用于查找和翻译Python错误信息
"""
import json
import re
from typing import List, Dict, Optional
class PythonErrorLookup:
def __init__(self, data_file: str = 'python_errors_data.json'):
"""初始化错误查询工具"""
self.data = self._load_data(data_file)
self.exceptions = self.data.get('exceptions', [])
self.categories = {cat['id']: cat for cat in self.data.get('categories', [])}
def _load_data(self, filename: str) -> Dict:
"""加载JSON数据"""
try:
with open(filename, 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
print(f"错误:找不到数据文件 {filename}")
return {}
except json.JSONDecodeError as e:
print(f"错误:JSON格式无效 - {e}")
return {}
def search_by_exception_name(self, name: str) -> Optional[Dict]:
"""根据异常名称查找"""
for exc in self.exceptions:
if exc['exception_name'].lower() == name.lower():
return exc
return None
def search_by_error_message(self, message: str) -> List[Dict]:
"""根据错误消息查找可能的异常"""
results = []
message_lower = message.lower()
for exc in self.exceptions:
for msg in exc.get('common_messages', []):
if message_lower in msg['message_en'].lower():
results.append({
'exception': exc,
'matched_message': msg
})
return results
def search_by_category(self, category_id: str) -> List[Dict]:
"""根据分类查找异常"""
return [exc for exc in self.exceptions if exc['category_id'] == category_id]
def get_all_categories(self) -> List[Dict]:
"""获取所有分类"""
return list(self.categories.values())
def format_exception_info(self, exc: Dict) -> str:
"""格式化异常信息显示"""
category = self.categories.get(exc['category_id'], {})
result = f"""
异常名称: {exc['exception_name']}
分类: {category.get('name_zh', exc['category_id'])}
英文描述: {exc['description_en']}
中文描述: {exc['description_zh']}
常见错误消息:"""
for i, msg in enumerate(exc.get('common_messages', []), 1):
result += f"""
{i}. 英文: {msg['message_en']}
中文: {msg['message_zh']}
场景: {msg['scenario']}
示例: {msg['example_code']}
解决: {msg['solution']}
"""
if exc.get('related_exceptions'):
result += f"\n相关异常: {', '.join(exc['related_exceptions'])}"
return result
def main():
"""主函数 - 交互式查询"""
lookup = PythonErrorLookup()
if not lookup.data:
print("无法加载数据,程序退出")
return
print("Python错误查询工具")
print("=" * 30)
print("命令:")
print(" 1. 输入异常名称 (如: ValueError)")
print(" 2. 输入错误消息片段 (如: division by zero)")
print(" 3. 输入 'categories' 查看所有分类")
print(" 4. 输入 'quit' 退出")
print()
while True:
query = input("请输入查询内容: ").strip()
if query.lower() == 'quit':
break
elif query.lower() == 'categories':
print("\n可用分类:")
for cat in lookup.get_all_categories():
print(f" {cat['id']}: {cat['name_zh']} - {cat.get('description_zh', '')}")
print()
continue
elif not query:
continue
# 尝试按异常名称查找
exc = lookup.search_by_exception_name(query)
if exc:
print(lookup.format_exception_info(exc))
print("-" * 50)
continue
# 尝试按错误消息查找
results = lookup.search_by_error_message(query)
if results:
print(f"\n找到 {len(results)} 个匹配的错误:")
for i, result in enumerate(results, 1):
print(f"\n{i}. {result['exception']['exception_name']}")
print(f" 匹配消息: {result['matched_message']['message_en']}")
print(f" 中文翻译: {result['matched_message']['message_zh']}")
print(f" 解决方案: {result['matched_message']['solution']}")
print("-" * 50)
continue
# 尝试按分类查找
category_results = lookup.search_by_category(query)
if category_results:
print(f"\n分类 '{query}' 中的异常:")
for exc in category_results:
print(f" - {exc['exception_name']}: {exc['description_zh']}")
print("-" * 50)
continue
print(f"未找到与 '{query}' 相关的信息")
print("-" * 50)
if __name__ == "__main__":
main()