Python 非类型对象不可调用(生成lexer)
我的代码:Python 非类型对象不可调用(生成lexer),python,python-3.x,lexer,re,Python,Python 3.x,Lexer,Re,我的代码: import re from collections import namedtuple class TokenDef(namedtuple("TokenDef", ("name", "pattern", "value_filter"))): def __repr_(self): return "TokenType." + self.name cla
import re
from collections import namedtuple
class TokenDef(namedtuple("TokenDef", ("name", "pattern", "value_filter"))):
def __repr_(self):
return "TokenType." + self.name
class TokenType(object):
_defs = [
TokenDef("plus", "+", None),
TokenDef("minus", "-", None),
TokenDef("aterisk", "*", None),
TokenDef("slash", "/", None),
TokenDef("left_paren", "(", None),
TokenDef("right_paren", ")", None),
TokenDef("integer", re.compile("[0-9]+"), int),
TokenDef("whitespace", re.compile("[ \t]+"), None),
]
for def_ in TokenType._defs:
setattr(TokenType, def_.name, def_)
token = namedtuple("Token", ("type", "value", "slice"))
def first_token(text, start=0):
match_text = text[start:]
token = None
token_text = None
for type_ in TokenType._defs:
name, pattern, value_filter = type_
if pattern is None:
continue
elif isinstance(pattern, str):
if not match_text.startswith:
continue
match_value = pattern
else:
match = pattern.match(match_text)
if not match:
continue
match_value = match.group(0)
if token_text is not None and len(token_text) >= len(match_value):
continue
token_text = match_value
if value_filter is not None:
match_value = value_filter(match_value)
token = token(type_, match_value, slice(start, start + len(token_text)))
return token
first_token("6")
我的错误:
Traceback (most recent call last):
File ".\lexer.py", line 64, in <module>
first_token("6")
File ".\lexer.py", line 60, in first_token
token = token(type_, match_value, slice(start, start + len(token_text)))
TypeError: 'NoneType' object is not callable
回溯(最近一次呼叫最后一次):
文件“\lexer.py”,第64行,在
第一个_标记(“6”)
文件“\lexer.py”,第60行,在第一个\u标记中
令牌=令牌(类型、匹配值、切片(开始、开始+len(令牌文本)))
TypeError:“非类型”对象不可调用
为什么会这样
我正在试着做一个词汇量表,我正在做一个教程,但是我找不到我的错误在哪里。我在jupyter笔记本上,使用Windows10Pro,我的python版本是3.9.0(anaconda环境)。什么是非类型对象?idk这很奇怪,但是idk。我看到了你的问题,你有两个不同的东西,叫做
令牌
token = namedtuple("Token", ("type", "value", "slice"))
如果要将其用作调用,请将另一个令牌重命名为类似于my_令牌的内容
更改以下行:
token = None
token = token(type_, match_value, slice(start, start + len(token_text)))
return token
到
您遵循的教程是什么?从您编写的
token=None
开始,那么token
就是None。所以您不能调用它。您分配了token=None
,然后尝试调用token()
。因此错误是我的芭蕾舞。这个人还写了token=None给@MarulForFlask好的,那么你的问题是什么?要么youtube视频出错,要么你没有完全复制他们的行为。确保您对token
的其他定义正确。In:print(first_token(“6”))out:token(type=TokenDef(name='plus',pattern='+',value='filter=None),value='+',slice=slice(0,1,None))@MarulForFlask我不知道您希望输出什么,我修复了您根据问题得到的错误我不希望输出为plus token,我将输出验证为int,值为6如果输入为6,输出不能为“+”,它需要为6,类型为int。@MarulForFlask所有这些都与您的问题无关确定我会查看它。
my_token = None
my_token = token(type_, match_value, slice(start, start + len(token_text)))
return my_token