Pyhon代码说明:
1.Pyhon代码里面没有{ }花括号
2.Python语句末尾;分号可省略
3.Pyhon语句的层次按照每行前面的缩进进行区分,同一个缩进层次从属于同一个代码段
缩进相同的代码类似于其它语言的同一个{}花括号里面的代码段
4.缩进可以是tab或空格,默认一个tab等于4个空格。为避免语法错误建议进行编码时只使用一种空格或tab
5.代码中:英语冒号表示下一个代码段,紧接着的下一行代码需要增加一级缩进
6.冒号使用的常见位置 if或else条件后面,for/while循环,类/函数定义后
C# Python常见语法错误检查代码
string GrammaCheck(string pyhonScript)
{
pyhonScript = pyhonScript.Replace("\r", "").Replace("\t", " ");
string[] lines = pyhonScript.Split('\n');
int LastSpaceCount = 0, NextSpaceCount = 0, CurrentCount = 0;
string temStart = "", temEnd = "", msg = "";
bool MustEqual = false;
for (int i = 0; i < lines.Length; i++)
{
CurrentCount = SpaceCount(lines[i]);
temEnd = lines[i].TrimEnd(new char[] { ' ' });
temStart = lines[i].TrimStart(new char[] { ' ' });
if (string.IsNullOrEmpty(temEnd))
continue;
if (temStart.StartsWith("#"))
continue;
if (CurrentCount < NextSpaceCount)
{
if (temStart.StartsWith("def ") || temStart.StartsWith("class "))
{
MustEqual = true;
NextSpaceCount = 4;
}
else if (temStart.StartsWith("else:") || temStart.StartsWith("else ") || temStart.StartsWith("elif "))
{
if (CurrentCount < NextSpaceCount - 4 && MustEqual)
{
msg += "Line:" + (i + 1) + " expect new line\r\n";
}
}
else if (MustEqual)
msg += "Line:" + (i + 1) + " expect new line\r\n";
}
else if (CurrentCount > NextSpaceCount)
{
msg += "Line:" + (i + 1) + " unexpected indent\r\n";
}
else if (CurrentCount == NextSpaceCount)
{
MustEqual = false;
}
if (temStart.StartsWith("def ") || temStart.StartsWith("class "))
{
if (CurrentCount != 0)
msg += "Line:" + (i + 1) + " unexpected space in front of the line\r\n";
if (!temEnd.EndsWith(":"))
{
msg += "Line:" + (i + 1) + " should end with ':'\r\n";
}
MustEqual = true;
NextSpaceCount = 4;
}
else if (temEnd.EndsWith(":"))
{
MustEqual = true;
NextSpaceCount = CurrentCount + 4;
}
else if (CurrentCount != 0)
{
NextSpaceCount = CurrentCount;
}
LastSpaceCount = CurrentCount;
}
if (msg == "")
msg = "Find No Error.";
return msg;
}
int SpaceCount(string line)
{
for (int i = 0; i < line.Length; i++)
{
if (line[i] != ' ')
return i;
}
return 0;
}