代码语法检查工具

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

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. 工具会显示具体的错误位置和描述

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

相关推荐
杜子不疼.10 分钟前
进程控制(四):自主Shell命令行解释器
linux·c语言·人工智能
橘颂TA12 分钟前
【Linux 网络】深入理解 UDP
linux·运维·服务器·网络·网络协议
乱蜂朝王7 小时前
Ubuntu 20.04安装CUDA 11.8
linux·运维·ubuntu
梁洪飞8 小时前
clk学习
linux·arm开发·嵌入式硬件·arm
Lw老王要学习9 小时前
Windows基础篇第一章_01VMware虚拟机安装window10
运维·windows·虚拟机
~光~~9 小时前
【嵌入式linux驱动——点亮led】基于鲁班猫4 rk3588s
linux·点灯·嵌入式linux驱动
yuanmenghao9 小时前
车载Linux 系统问题定位方法论与实战系列 - 车载 Linux 平台问题定位规范
linux·运维·服务器·网络·c++
qq_5895681011 小时前
centos6.8镜像源yum install不成功,无法通过镜像源下载的解决方式
linux·运维·centos
我是苏苏11 小时前
C#高级:使用ConcurrentQueue做一个简易进程内通信的消息队列
java·windows·c#
weixin_5160230711 小时前
linux下fcitx5拼音的安装
linux·运维·服务器