PLY LEX和YACC的问题

时间:2016-02-22 22:52:58

标签: python parsing yacc lex ply

我正在尝试运行PLY简单示例的第一部分,但我遇到了一个奇怪的错误。当我运行以下代码时,它给我一个关于lex.lex()的错误 谁知道问题是什么?

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-e527bd224769> in <module>()
     14     return t
     15 
---> 16 ply.lex.lex() # Build the lexer

c:\python27\lib\site-packages\ply\lex.pyc in lex(module, object, debug, optimize, lextab, reflags, nowarn, outputdir, debuglog, errorlog)
    904     linfo.get_all()
    905     if not optimize:
--> 906         if linfo.validate_all():
    907             raise SyntaxError("Can't build lexer")
    908 

c:\python27\lib\site-packages\ply\lex.pyc in validate_all(self)
    578         self.validate_tokens()
    579         self.validate_literals()
--> 580         self.validate_rules()
    581         return self.error
    582 

c:\python27\lib\site-packages\ply\lex.pyc in validate_rules(self)
    820 
    821         for module in self.modules:
--> 822             self.validate_module(module)
    823 
    824     # -----------------------------------------------------------------------------

c:\python27\lib\site-packages\ply\lex.pyc in validate_module(self, module)
    831 
    832     def validate_module(self, module):
--> 833         lines, linen = inspect.getsourcelines(module)
    834 
    835         fre = re.compile(r'\s*def\s+(t_[a-zA-Z_0-9]*)\(')

c:\python27\lib\inspect.pyc in getsourcelines(object)
    688     original source file the first line of code was found.  An IOError is
    689     raised if the source code cannot be retrieved."""
--> 690     lines, lnum = findsource(object)
    691 
    692     if ismodule(object): return lines, 0

c:\python27\lib\inspect.pyc in findsource(object)
    524     is raised if the source code cannot be retrieved."""
    525 
--> 526     file = getfile(object)
    527     sourcefile = getsourcefile(object)
    528     if not sourcefile and file[:1] + file[-1:] != '<>':

c:\python27\lib\inspect.pyc in getfile(object)
    401         if hasattr(object, '__file__'):
    402             return object.__file__
--> 403         raise TypeError('{!r} is a built-in module'.format(object))
    404     if isclass(object):
    405         object = sys.modules.get(object.__module__)

TypeError: <module '__main__' (built-in)> is a built-in module

这是错误:

soup.get_text()

2 个答案:

答案 0 :(得分:5)

您正试图从某种REPL(ply开始)运行ipython

无论出于何种原因,这都不会奏效。 Ply坚持认为语法是一个模块,这意味着它必须在一个文件中。该错误精确地表明没有与语法源相关联的文件。

答案 1 :(得分:5)

事实证明,问题在于我是通过iPython Notebook运行代码的,并且出于某种原因它并不喜欢它。将代码保存为常规.py文件并通过命令提示符运行它并且没有发生错误!

P.S。如果有人能详细说明为什么代码不能在iPython Notebook环境中运行,我感激不尽!