代码语法检查工具

为了帮助您检查和修复这类问题,我将为您创建一个代码语法检查工具,它可以扫描您的代码文件,找出可能的语法错误和未正确引用的字符串。

python 复制代码
#!/usr/bin/env python3
"""
代码语法检查工具
用于检测Python代码中的语法错误和常见问题
"""

import ast
import sys
import os

def check_syntax(file_path):
    """
    检查Python文件的语法错误
    
    Args:
        file_path: 要检查的Python文件路径
        
    Returns:
        list: 错误信息列表,如果没有错误则返回空列表
    """
    errors = []
    
    if not os.path.exists(file_path):
        return [f"错误: 文件 '{file_path}' 不存在"]
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
    except UnicodeDecodeError:
        try:
            with open(file_path, 'r', encoding='gbk') as f:
                content = f.read()
        except:
            return [f"错误: 无法读取文件 '{file_path}',请检查文件编码"]
    
    # 尝试使用ast模块解析代码(检测语法错误)
    try:
        ast.parse(content)
    except SyntaxError as e:
        errors.append(f"语法错误在第 {e.lineno} 行, 第 {e.offset} 列: {e.msg}")
        errors.append(f"错误附近的内容: {e.text}")
    
    # 检查是否有未闭合的引号
    lines = content.split('\n')
    in_string = False
    string_char = None
    for i, line in enumerate(lines, 1):
        j = 0
        while j < len(line):
            char = line[j]
            
            # 处理转义字符
            if char == '\\' and j + 1 < len(line):
                j += 2
                continue
            
            # 检查字符串开始/结束
            if char in ('"', "'"):
                if not in_string:
                    in_string = True
                    string_char = char
                elif string_char == char:
                    in_string = False
                    string_char = None
            
            j += 1
        
        # 如果行结束时仍在字符串中,检查下一行是否继续
        if in_string and i < len(lines):
            # 检查下一行是否以相同的字符串字符开始
            next_line = lines[i]
            if next_line and next_line[0] != string_char:
                # 尝试查找字符串结束
                found_end = False
                for k, ch in enumerate(next_line):
                    if ch == string_char and (k == 0 or next_line[k-1] != '\\'):
                        found_end = True
                        break
                
                if not found_end:
                    errors.append(f"警告: 第 {i} 行可能有未闭合的字符串引号 (使用 {string_char})")
    
    # 检查是否有看起来像自然语言文本的行(没有Python语法结构)
    for i, line in enumerate(lines, 1):
        line_stripped = line.strip()
        
        # 跳过空行和注释
        if not line_stripped or line_stripped.startswith('#'):
            continue
        
        # 检查是否包含像"KFC CrazyThursday need 50RMB"这样的文本
        # 这些通常缺少引号,看起来像自然语言
        words = line_stripped.split()
        if len(words) >= 3:
            # 检查是否看起来像自然语言(包含多个单词但没有Python操作符或关键字)
            has_python_ops = any(op in line for op in ['=', '+', '-', '*', '/', '==', '!=', '>', '<', '>=', '<=', '(', ')', '{', '}', '[', ']'])
            has_python_keywords = any(keyword in line for keyword in ['def', 'class', 'if', 'else', 'for', 'while', 'import', 'from', 'return'])
            
            if not has_python_ops and not has_python_keywords and not ('"' in line or "'" in line):
                # 可能是一个未加引号的字符串
                errors.append(f"警告: 第 {i} 行可能包含未加引号的文本: {line_stripped[:50]}...")
    
    return errors

def main():
    """主函数"""
    print("代码语法检查工具")
    print("=" * 50)
    
    # 测试用例1: 检查当前目录下的test_code.py文件
    test_file = "test_code.py"
    
    # 创建一个有语法错误的测试文件
    test_code = '''def example_function():
    # 这是一个正确的函数
    x = 10
    y = 20
    result = x + y
    return result

# 这里有一个语法错误 - 未闭合的字符串
message = "Hello, World

# 这里可能有一个未加引号的字符串
KFC CrazyThursday need 50RMB

# 正常的代码
print("程序结束")
'''
    
    # 写入测试文件
    with open(test_file, 'w', encoding='utf-8') as f:
        f.write(test_code)
    
    print(f"创建测试文件: {test_file}")
    print(f"检查文件: {test_file}")
    print("-" * 50)
    
    # 检查语法
    errors = check_syntax(test_file)
    
    if errors:
        print(f"在 {test_file} 中发现了 {len(errors)} 个问题:")
        for i, error in enumerate(errors, 1):
            print(f"{i}. {error}")
    else:
        print(f"{test_file} 语法正确!")
    
    print("\n" + "=" * 50)
    
    # 让用户检查自己的文件
    print("\n要检查您自己的文件,请将文件路径作为参数传递:")
    print(f"示例: python {sys.argv[0]} your_script.py")
    
    if len(sys.argv) > 1:
        user_file = sys.argv[1]
        print(f"\n检查用户文件: {user_file}")
        print("-" * 50)
        
        user_errors = check_syntax(user_file)
        
        if user_errors:
            print(f"在 {user_file} 中发现了 {len(user_errors)} 个问题:")
            for i, error in enumerate(user_errors, 1):
                print(f"{i}. {error}")
        else:
            print(f"{user_file} 语法正确!")
    
    # 清理测试文件
    if os.path.exists(test_file):
        os.remove(test_file)
        print(f"\n已清理测试文件: {test_file}")

if __name__ == "__main__":
    main()

关键点说明:

  1. 语法分析 : 使用Python的ast模块进行正式的语法解析,能够准确检测大多数语法问题。

  2. 字符串引号检查: 专门检查未闭合的字符串引号,这是常见的错误原因。

  3. 自然语言检测: 尝试检测代码中可能误写的自然语言文本(如示例中的"KFC CrazyThursday need 50RMB")。

  4. 错误定位: 提供具体的行号和列号,帮助您快速定位问题。

使用方法:

  1. 将上面的代码保存为code_syntax_checker.py

  2. 运行脚本检查您的代码文件: python code_syntax_checker.py 您的文件.py

  3. 工具会显示具体的错误位置和描述

这个工具能帮助您找出代码中的语法错误,特别是像未加引号的字符串这类问题。请运行此工具检查您出错的代码文件,然后根据提示修复相关问题。

相关推荐
Halo_tjn2 小时前
虚拟机相关实验概述
java·开发语言·windows·计算机
霍夫曼3 小时前
UTC时间与本地时间转换问题
java·linux·服务器·前端·javascript
月熊4 小时前
在root无法通过登录界面进去时,通过原本的普通用户qiujian如何把它修改为自己指定的用户名
linux·运维·服务器
programer_334 小时前
本地手动创建一个MCP(windows环境)
windows·python·ai·mcp·cherry studio
曹牧4 小时前
Java:List<Map<String, String>>转换为字符串
java·开发语言·windows
大江东去浪淘尽千古风流人物5 小时前
【DSP】向量化操作的误差来源分析及其经典解决方案
linux·运维·人工智能·算法·vr·dsp开发·mr
打码人的日常分享5 小时前
智慧城市一网统管建设方案,新型城市整体建设方案(PPT)
大数据·运维·服务器·人工智能·信息可视化·智慧城市
赖small强5 小时前
【Linux驱动开发】NOR Flash 技术原理与 Linux 系统应用全解析
linux·驱动开发·nor flash·芯片内执行
风掣长空6 小时前
Google Test (gtest) 新手完全指南:从入门到精通
运维·服务器·网络