类型错误:不能迭代非序列
我看了很多关于这个问题的帖子,也在网上查了一些资料。我之前用过其他编程语言,但现在正在学习Python,而且对类的理解还不够,所以我觉得我可能对类的运作方式有些不明白。
我想开发一个电子书阅读应用,找到了Roberto Alasina的一个项目叫做integrate,这个项目是个不错的起点,但它没有收集元数据,而且处理电子书的库也不够完善,无法满足我想做的其他功能。所以我找到了dustjacket,这是一个处理电子书的类。
我需要进一步提取数据,因为我需要从应用的多个部分读取数据,而不仅仅是阅读器本身。我计划添加whoosh来实现搜索功能,并且为了索引,我需要读取章节内容,然后对文件进行索引。我可以在导入书籍时完成这个过程,实际上不需要图形界面来处理索引部分。
总之,在dustjacket中,我添加了日志记录,现在我可以看到我的方法正确地从电子书中获取了目录:
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
我加入了调试日志,可以很清楚地看到实例是正确地从类中调用的,标题和内容文件也都存在。这是来自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
到目前为止,我完全不知道自己哪里出错了,为什么这个方法不工作。如果这些信息不够,我可以把我使用的其他类的代码发上来。
谢谢!
1 个回答
0
你遇到的问题,正如你所展示的,是这一行:
for l, c in self.__toc:
但是 self.__toc 被声明为:
self.__toc = EpubToc(self)
总的来说,你需要遍历一个列表,而不是一个对象。像这样做应该可以,你可能需要稍微调整一下,以适应你的具体需求(比如可能需要用到 zip 函数)
for c in self.__toc.get_chapter_titles():