Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
删除标题的Python正则表达式_Python_Regex - Fatal编程技术网

删除标题的Python正则表达式

删除标题的Python正则表达式,python,regex,Python,Regex,我从网页上抓取了以下文本: 据信,一名25岁左右的女性在监狱中被捕 2011年,她在马来西亚婆罗洲放荡,余生都生活在 沙巴的塔宾野生动物保护区,一个由宝来管理的围栏设施。 [caption id=“attachment_194682”align=“aligncenter”width=“768”]Rhino 在婆罗洲犀牛保护区接受照顾。照片由沙巴提供 野生动物部。[/说明]总体而言,在 极端濒危物种被认为仍然存在 您可以看到标题的方括号之间有文本。基本上,我想删除方括号和句子之间的所有内容 在婆罗

我从网页上抓取了以下文本:

据信,一名25岁左右的女性在监狱中被捕 2011年,她在马来西亚婆罗洲放荡,余生都生活在 沙巴的塔宾野生动物保护区,一个由宝来管理的围栏设施。 [caption id=“attachment_194682”align=“aligncenter”width=“768”]Rhino 在婆罗洲犀牛保护区接受照顾。照片由沙巴提供 野生动物部。[/说明]总体而言,在 极端濒危物种被认为仍然存在

您可以看到标题的方括号之间有文本。基本上,我想删除方括号和句子之间的所有内容

在婆罗洲犀牛保护区照顾犀牛。照片由 沙巴野生动物部

因为它是图像的标题。因此,结果应该是:

据信,一名25岁左右的女性在监狱中被捕 2011年,她在马来西亚婆罗洲放荡,余生都生活在 沙巴的塔宾野生动物保护区,一个由宝来管理的围栏设施。 总的来说,55到100种极度濒危物种 据信仍然


我该怎么做?

您可以使用python
re
模块在标题之间获取数据,如下所示:

import re
text = """
A female believed to be around 25 years old, she was captured in the wild in Malaysian Borneo in 2011 and lived the rest of her life at the Tabin Wildlife Reserve in Sabah, a fenced-in facility managed by BORA. [caption id="attachment_194682" align="aligncenter" width="768"] Rhino being cared for at the Borneo rhino sanctuary. Photo courtesy of Sabah Wildlife Department.[/caption] Overall, between 55 and 100 of the Critically Endangered species are believed to remain
"""

pattern = r'\[caption.*\](.*)\[/caption\]'
items = re.search(pattern, text)
print text.replace(items.group(0), '')

#  A female believed to be around 25 years old, she was captured in the wild in Malaysian Borneo in 2011 and lived the rest of her life at the Tabin Wildlife Reserve in Sabah, a fenced-in facility managed by BORA.  Overall, between 55 and 100 of the Critically Endangered species are believed to remain

这不是正则表达式编写服务。你自己做了什么努力来解决这个问题?哦,我想是的。我在这个网站上用python正则表达式尝试了几种解决方案,但都没有成功。我认为不是,你收到的反对票表明我是正确的。你让人为你写的事实并不能改变这不是一个代码编写服务的事实,如果你继续尝试将它视为一个服务,它将不适合你。@KenWhite哦,对不起,我以为你的意思是标签错了。事实上,我用正则表达式尝试了一些解决方案,但我对python正则表达式不太了解,这就是我在这里寻求帮助的原因。这就是为什么我要求你们展示你们已经尝试过的,作为你们问题的一部分。这表明你付出了努力。有关零努力问题的讨论(包括请为我的帖子编写代码)以及为什么它们不适合此处,请参阅。请查看我编辑的问题。“我想在[标题]区域之外获取文本。@lenhhoxung编辑了我的回答,非常感谢。”。