【问题标题】:How to find multiple strings between tag/sub-strings?如何在标签/子字符串之间查找多个字符串?
【发布时间】:2019-12-04 18:17:50
【问题描述】:

我有一个字符串,它围绕特定的单词或子字符串定义了标签。例如:

text = 'Bring me to <xxx>ibis and the</xxx> in <ccc>NW</ccc> and the <sss>Jan</sss> 
<hhh>10</hhh>'

如何获取字符串&lt;xxx&gt;ibis and the&lt;/xxx&gt;&lt;ccc&gt;NW&lt;/ccc&gt;&lt;sss&gt;Jan&lt;/sss&gt;&lt;hhh&gt;10&lt;/hhh&gt;。这些标签可以是任何东西,但覆盖一个词或几个词的标签将是相似的。此外,如果缺少开始或结束标记,我不希望返回该字符串。例如:

text = 'Bring me to <xxx>ibis and the in NW</ccc> and the <sss>Jan</sss> 
<hhh>10</hhh>'

在这种情况下,只需要返回&lt;sss&gt;Jan&lt;/sss&gt;&lt;hhh&gt;10&lt;/hhh&gt;

【问题讨论】:

  • 为什么标记为nsregularexpression?你是在 iOS 上运行 Python 还是什么?
  • @Mast 已更正!

标签: regex python-3.x string substring


【解决方案1】:

通常,您不希望正则表达式解析 (X)HTML (more info in this answer) 更好的选择是使用解析器。这个例子是beautifulsoup:

data = '''text = 'Bring me to <xxx>ibis and the</xxx> in <ccc>NW</ccc> and the <sss>Jan</sss>
<hhh>10</hhh>'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(data, 'html.parser')

for tag in soup.select('xxx, ccc, sss, hhh'):
    print(tag.get_text(strip=True))

打印:

ibis and the
NW
Jan
10

编辑:获取整个标签字符串:

for tag in soup.select('xxx, ccc, sss, hhh'):
    print(tag)

打印:

<xxx>ibis and the</xxx>
<ccc>NW</ccc>
<sss>Jan</sss>
<hhh>10</hhh>

编辑二:如果您有要查找的标签列表:

list_of_tags = ['xxx', 'ccc', 'sss', 'hhh']
for tag in soup.find_all(list_of_tags):
    print(tag)

编辑:如果 HTML 格式不正确,则需要更改解析器:

data = '''text = 'Bring me to <xxx>ibis and the in NW</ccc> and the <sss>Jan</sss>
<hhh>10</hhh>'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(data, 'lxml')

list_of_tags = ['xxx', 'ccc', 'sss', 'hhh']
for tag in soup.find_all(list_of_tags):
    if tag.find_all(list_of_tags):
        continue
    print(tag)

打印:

<sss>Jan</sss>
<hhh>10</hhh>

【讨论】:

  • 你的答案是正确的。但我很抱歉我应该以另一种方式问我的问题。我现在编辑了,你能检查一下吗?
  • 如何给标签命名?因为当我将它们作为列表提供时,我得到了TypeError: unhashable type: 'list'
  • @Dennis.M 你使用方法find_all() 看我的回答。 BeautifulSoup 的文档可以在这里找到crummy.com/software/BeautifulSoup/bs4/doc
  • 如果缺少其中一个标签,如何避免解析字符串?
  • @Dennis.M 你是什么意思?如果仅缺少一个,您是要返回所有标签还是不返回任何标签?
猜你喜欢
  • 2014-12-07
  • 2011-03-23
  • 2015-09-16
  • 2015-06-27
  • 2021-07-02
  • 2020-05-28
  • 2013-09-13
相关资源
最近更新 更多