我目前遇到了 NoneType 的问题并在 Python 中使用函数 isalpha() 。我想做的是词法分析,我想将整个代码分为四类。这是我的代码
import sys
import keyword #keyword.iskeyword()
**strong text**def check_chars(tmp,x):
if (tmp == "" or tmp.isalpha()) and (x =="" or x.isalpha()):
if keyword.iskeyword(tmp):
print("Key: "+ tmp)
return ""
return tmp+x
if tmp.isalpha() and not x.isalpha():
print("Var: "+tmp)
return x
separators = ['(',')','[',']','{','}',',',':','.',';','@','=','->','+=','-=','*=','/=','//=','%=','@=','&=','|=','^=','>>=','<<=','**=']
operators = ['+','-','*','**','/','//','%','<<','>>','&','|','^','~','<','>','<=','>=','==','!=']
f = open(sys.argv[1],'r')
program = f.read()
tmp = ""
for x in program:
tmp = check_chars(tmp,x)
if tmp in separators:
print("Sep: "+ tmp)
tmp = ""
if tmp in operators:
print("Ope: "+ tmp)
tmp = ""
if x is " ":
tmp = ""
当我到达示例程序中第一行的末尾时:
def funkce(a,b):
c=''
a**=b
if a<b:
print('ahoj\'ky',a)
else:
print(0xff,0b11101,0o777,.90e-10,123E+5,c)
print('''To je dlouhy
retezec pres mnoho
radku''')
funkce(-256+356,.85**.33)
发生错误:
Traceback (most recent call last):
File "HW09.py", line 24, in <module>
tmp = check_chars(tmp,x)
File "HW09.py", line 5, in check_chars
if (tmp == "" or tmp.isalpha()) and (x =="" or x.isalpha()):
AttributeError: 'NoneType' object has no attribute 'isalpha'
如果错误在程序开始时出现,我不会感到惊讶。但是它怎么可能在行尾上升呢?错误是否可能与行尾字符“\n”有关。谢谢你的建议:)