【发布时间】:2020-07-16 13:15:28
【问题描述】:
问题
对于 Markdown 文档,我想过滤掉列表 to_keep 中标题标题为 not 的所有部分。一个部分由一个标题和正文组成,直到下一个部分或文档的结尾。为简单起见,我们假设文档只有 1 级标题。
当我对当前元素是否已在 to_keep 中的标头之前进行简单区分并执行 return None 或 return [] 时,我得到一个错误。也就是说,对于pandoc --filter filter.py -o output.pdf input.md,我得到TypeError: panflute.dump needs input of type "panflute.Doc" but received one of type "list"(代码、示例文件和最后的完整错误消息)。
我使用 Python 3.7.4 和 panflute 1.12.5 和 pandoc 2.2.3.2。
问题
如果对何时执行return [] 进行更细粒度的区分,它会起作用(函数action_working)。 我的问题是,为什么需要这种更细粒度的区分?我的解决方案似乎可以工作,但这很可能是偶然的……我怎样才能让它正常工作?
文件
错误
Traceback (most recent call last):
File "filter.py", line 42, in <module>
main()
File "filter.py", line 39, in main
return run_filter(action_not_working, doc=doc)
File "C:\Users\ody_he\AppData\Local\Continuum\anaconda3\lib\site-packages\panflute\io.py", line 266, in run_filter
return run_filters([action], *args, **kwargs)
File "C:\Users\ody_he\AppData\Local\Continuum\anaconda3\lib\site-packages\panflute\io.py", line 253, in run_filters
dump(doc, output_stream=output_stream)
File "C:\Users\ody_he\AppData\Local\Continuum\anaconda3\lib\site-packages\panflute\io.py", line 132, in dump
raise TypeError(msg)
TypeError: panflute.dump needs input of type "panflute.Doc" but received one of type "list"
Error running filter filter.py:
Filter returned error status 1
输入.md
# English
Some cool english text this is!
# Deutsch
Dies ist die deutsche Übersetzung!
# Sources
Some source.
# Priority
**Medium** *[Low | Medium | High]*
# Status
**Open for Discussion** *\[Draft | Open for Discussion | Final\]*
# Interested Persons (mailing list)
- Franz, Heinz, Karl
fiter.py
from panflute import *
to_keep = ['Deutsch', 'Status']
keep_current = False
def action_not_working(elem, doc):
'''For every element we check if it occurs in a section we wish to keep.
If it is, we keep it and return None (indicating to keep the element unchanged).
Otherwise we remove the element (return []).'''
global to_keep, keep_current
update_keep(elem)
if keep_current:
return None
else:
return []
def action_working(elem, doc):
global to_keep, keep_current
update_keep(elem)
if keep_current:
return None
else:
if isinstance(elem, Header):
return []
elif isinstance(elem, Para):
return []
elif isinstance(elem, BulletList):
return []
def update_keep(elem):
'''if the element is a header we update to_keep.'''
global to_keep, keep_current
if isinstance(elem, Header):
# Keep if the title of a section is in too keep
keep_current = stringify(elem) in to_keep
def main(doc=None):
return run_filter(action_not_working, doc=doc)
if __name__ == '__main__':
main()
【问题讨论】:
标签: python filter pandoc panflute