【发布时间】:2016-07-27 14:57:48
【问题描述】:
如何使用 Python 从文档中提取所有 HTML 样式的 cmets?
我尝试过使用正则表达式:
text = 'hello, world <!-- comment -->'
re.match('<!--(.*?)-->', text)
但它什么也没产生。我不明白这一点,因为相同的正则表达式在 https://regex101.com/ 的同一字符串上运行良好
更新:我的文档实际上是一个XML文件,我正在用pyquery(基于lxml)解析文档,但我不认为lxml可以extract comments that aren't inside a node。这是文档的样子:
<?xml version="1.0" encoding="UTF-8"?>
<clinical_study rank="220398">
<intervention_browse>
<!-- CAUTION: The following MeSH terms are assigned with an imperfect algorithm -->
<mesh_term>Freund's Adjuvant</mesh_term>
<mesh_term>Keyhole-limpet hemocyanin</mesh_term>
</intervention_browse>
<!-- Results have not yet been posted for this study -->
</clinical_study>
更新 2:感谢您提出其他答案,但我已经使用 lxml 广泛解析文档,并且不想用 BeautifulSoup 重写所有内容。已相应更新标题。
【问题讨论】:
-
使用 lxml 或 beautifulsoup 会更简单且更可靠
-
@MaxU 我已经在使用 lxml (pyquery),所以我真的不想切换到 BeautifulSoup,但谢谢。我已经更新了问题,明确表示我很乐意使用正则表达式或 lxml。
-
@Padraic 我不确定在 lxml 中是否真的可行,请参阅更新。
-
@Richard dox 您链接到建议您可以确定
tag是否是etree.comment- 你试过吗?然后如果True可以打印tag属性值? -
@DavidZemens 的问题是没有
tag,评论只是浮动的。