【问题标题】:TypeError: iteration over non-sequenceTypeError:对非序列的迭代
【发布时间】:2013-01-29 14:16:18
【问题描述】:

我在这里查看了很多关于此的帖子,并在谷歌上搜索它。我使用过其他语言,但仍在学习 Python,而且我对类也不熟悉,所以我认为我只是不了解类的行为方式。

我想开发一个 epub 阅读应用程序,发现 roberto alasina 的项目称为集成,这是一个很好的起点,但它没有收集元数据,而且 epub 处理库的提取不足以用于我的其他一些事情想要做。所以我找到了防尘套,它是一个 epub 阅读课。

我需要进一步提取它的原因是我需要处理来自应用程序多个部分的数据读取,而不仅仅是读取器本身。我计划向它添加 whoosh 以启用搜索和索引,我需要阅读章节然后索引文件。我可以在导入图书的过程中执行此操作,并且实际上不需要用于实际索引部分的 gui。

无论如何,我在 dist 夹克中添加了日志记录,我可以看到我的方法正确地从 epub 中获取目录:

    def __parse_oebps(self, epub):
    '''Construct the chapter list assuming that the ePub has files in OEBPS/.'''

    # Parse the chapters
    npoints = self.__toc.findall("//{%(tocns)s}navPoint" % {'tocns': self.__namespaces['ncx']})
    for p in npoints:                   
        #rt = p.getroottree()
        #title = p.findtext("{%(tocns)s}text" % {'tocns': self.__namespaces['ncx']}) # Label text           
        title = p.find(
            '{http://www.daisy.org/z3986/2005/ncx/}navLabel').find(
                '{http://www.daisy.org/z3986/2005/ncx/}text').text
        contentfile = p.find("{%(tocns)s}content[@src]" % {'tocns':self.__namespaces['ncx']}).attrib['src'] # Contentfile name
        #if self.__has_oebps:
        #   #contentfile = "OEBPS/" + contentfile
        #   contentfile = "OEBPS/" + contentfile
        #   log.info("content file: %s", contentfile)

        #return contentfile 
        #self.chapters.append(EpubChapter(epub, p.attrib['id'], p.attrib['playOrder'], contentfile, title))
        if title and contentfile:
            log.debug("Title:        %s", title)
            log.debug("content file: %s", contentfile)
            self.chapters.append([title, contentfile])

    return self.chapters

我输入了调试日志,可以很容易地看到从类中正确调用了实例,并且标题和内容文件在那里。 this 来自 ebubtoc 类,并从 epub 类中的此方法调用:

    def __read_toc(self):
    '''Construct the table of contents for this epub'''
    self.__toc = EpubToc(self)
    for l, c in self.__toc:
        log.debug("Title:        %s", l)
        log.debug("content file: %s", c)

现在当这个方法获取数据的时候就是我得到这个错误的时候:

    for l, c in self.__toc:
TypeError: iteration over non-sequence

目前我不知道我做错了什么以及为什么这不起作用。如果这还不够,我可以发布我正在使用的其余课程。

谢谢

【问题讨论】:

  • 你能发布完整的回溯,而不仅仅是最后两行吗?
  • 你能在 for 循环之前print(self.__toc) 并显示输出吗?
  • __toc = None 从类的顶部和 print 语句确实返回 None 我也在顶部尝试了 __toc = [] 但仍然遇到同样的问题

标签: python xml-parsing lxml epub


【解决方案1】:

正如您所展示的,您的问题是这一行:

for l, c in self.__toc:

但是 self.__toc 被声明为:

self.__toc = EpubToc(self)

底线是,您需要遍历一个列表,而不是一个对象。这样的东西应该可以工作,您可能需要进行一些调整才能使其满足您的特定需求(例如,可能是 zip 功能)

for c in self.__toc.get_chapter_titles():

【讨论】:

  • 基于一些快速测试,在我看来self.__toc 是一个自定义(旧式)类——这是我能够设法获得 OP 的确切回溯消息的唯一方法。
  • 不完全确定你在这里指的是什么,但你可以从我上面的帖子中看到它返回的确切内容 self.chapters.append([title, contentfile])
猜你喜欢
  • 2015-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-09
  • 2018-08-06
  • 2015-10-23
  • 2013-09-01
  • 2020-07-12
相关资源
最近更新 更多