在Python中解析caption标记中的文本

2024-04-25 00:43:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将wordpress博客迁移到Jekyll的过程中遇到以下障碍:

我想分析文本,如

[caption id="attachment_1749417" align="aligncenter" width="426"][![femur head cross section](http://www.wired.com/wp-content/uploads/2015/03/femur-head-cross-section.png)](http://www.bartleby.com/107/illus247.html) A cross-section of the top of the thigh bone. ![](http://www.wired.com/wp-content/themes/Phoenix/assets/images/gallery-cam@2x.png) [Gray's Anatomy](http://www.bartleby.com/107/illus247.html) / Public Domain[/caption]

所以我恢复了标题标签之间的所有文本,即

[![femur head cross section](http://www.wired.com/wp-content/uploads/2015/03/femur-head-cross-section.png)](http://www.bartleby.com/107/illus247.html) A cross-section of the top of the thigh bone. ![](http://www.wired.com/wp-content/themes/Phoenix/assets/images/gallery-cam@2x.png) [Gray's Anatomy](http://www.bartleby.com/107/illus247.html) / Public Domain

我尝试了以下Python代码:

match = re.search("\[caption.*\](.*)\[\/caption\]",caption)
if match and len(match.groups()) > 0:
    actualcaption = match.groups()[0]
    print 'actual caption: '+ actualcaption

然而,这只给了我(http://www.bartleby.com/107/illus247.html) / Public Domain

任何帮助都将不胜感激!谢谢。你知道吗


Tags: comhttppnghtmlwwwsectioncontenthead
1条回答
网友
1楼 · 发布于 2024-04-25 00:43:04

主要问题是

  • 您正在访问match.groups()[0],而您应该访问match.group(1),因为您用模式中的一对无转义括号捕获了所需的部分,并且它们是唯一一对捕获括号,因此ID=1。你知道吗
  • 您将贪婪量词与.*一起使用,同时需要.*?尽可能少地匹配除换行符以外的字符

注意:如果文本跨越多行,还应该将re.DOTALLre.S传递给^{},以便.可以匹配换行符。你知道吗

参见regex demoPython demo

import re
regex = r"\[caption.*?](.*?)\[/caption]"
test_str = "[caption id=\"attachment_1749417\" align=\"aligncenter\" width=\"426\"][![femur head cross section](http://www.wired.com/wp-content/uploads/2015/03/femur-head-cross-section.png)](http://www.bartleby.com/107/illus247.html) A cross-section of the top of the thigh bone. ![](http://www.wired.com/wp-content/themes/Phoenix/assets/images/gallery-cam@2x.png) [Gray's Anatomy](http://www.bartleby.com/107/illus247.html) / Public Domain[/caption]"
match = re.search(regex, test_str)
if match:
    print(match.group(1))

打印:

[![femur head cross section](http://www.wired.com/wp-content/uploads/2015/03/femur-head-cross-section.png)](http://www.bartleby.com/107/illus247.html) A cross-section of the top of the thigh bone. ![](http://www.wired.com/wp-content/themes/Phoenix/assets/images/gallery-cam@2x.png) [Gray's Anatomy](http://www.bartleby.com/107/illus247.html) / Public Domain

相关问题 更多 >