代码报错list indices must be integers or slices, not str,求ePub锚标签场景解决方案
解决ePub XML输出锚标签时的列表索引错误
嘿,我来帮你拆解这个问题~你遇到的list indices must be integers or slices, not str报错,本质是你尝试用字符串去索引一个列表,而列表只能用整数(比如[0])或者切片(比如[1:3])来定位元素。
咱们聚焦到第208行的代码:
if [currentpage]["headingAnchorName"][currentanchor] in data["pages"]:
这里大概率是以下两种情况之一:
currentpage["headingAnchorName"]是一个列表,但你用currentanchor这个字符串去索引它(比如["anchor1"]这种形式,而不是[0]);- 不小心把
currentpage写成了[currentpage](多了一层列表包裹),导致后续索引操作失效。
结合你提到的toc.ncx和metadata.json场景,给你几个具体的排查和修复方向:
1. 先确认数据结构
在报错代码前加几行调试代码,打印关键变量的类型和内容:
print(type(currentpage), currentpage) print(type(currentpage["headingAnchorName"]), currentpage["headingAnchorName"]) print(type(currentanchor), currentanchor)
运行后你就能清楚看到:
currentpage["headingAnchorName"]到底是列表还是字典;currentanchor的值是不是你预期的索引(整数)还是锚点名称(字符串)。
2. 针对常见场景的修复
如果currentpage["headingAnchorName"]是存储锚点名称的列表(比如从ncx的navPoint节点里解析出来的多个锚点),那你应该遍历列表元素,而不是用字符串索引:
# 遍历所有锚点,检查是否存在于data["pages"]中 for anchor in currentpage["headingAnchorName"]: if anchor in data["pages"]: # 执行你的逻辑 pass
如果headingAnchorName本应是字典(键为锚点标识,值为锚点名称),那你需要检查解析toc.ncx的代码,是不是把字典结构错误地转成了列表。
3. 检查data["pages"]的结构
另外,确认data["pages"]的类型:如果它是字典,in操作会检查键是否存在;如果是列表,会检查元素是否存在。根据你的业务逻辑调整判断方式。
内容的提问来源于stack exchange,提问作者Hal Motley
相关产品推荐
相关产品推荐

