【问题标题】:How to split HTML text ignoring spaces in tags如何拆分 HTML 文本忽略标签中的空格
【发布时间】:2016-01-09 13:21:34
【问题描述】:

我有这样的html文本:

myHTML = 'I like <a class="thing1 thing2">this thing</a>'
myHTMLarray = myHTML.Split(' ')
>>>['I','like','<a','class="thing1','thing2">this','thing</a>']

我需要忽略标签中的空格('' 之间的任何内容)。我想要的结果是:

>>>['I','like','<a class="thing1 thing2">this','thing</a>']

理想情况下,我想确保文本中的一个单词恰好出现在列表的每个元素中。因此,没有空格以外的文本的中断标签或跨度标签将包含在前一个单词中。

【问题讨论】:

  • 也许我可以做一些正则表达式来让 split() 忽略标签中的空格?
  • @Matzyschneider 我实际上不希望标签作为不同的元素。我希望它们包含在文本中的一个单词中。我很好

    firstword 都在一个元素中

  • crummy.com/software/BeautifulSoup/bs4/doc 可能有帮助:) 或者在这里你可以试试你的正则表达式 :P pythex.org
  • 我想过做一些类似 soup.string.split(' ') 的事情,但我不确定如何将 html 标签放回列表中。

标签: python list split


【解决方案1】:

基本上你想忽略标签内的空格。为此,您需要跟踪开始和结束标记尖括号,并检测其他地方出现的空格,而不是括号之间的空格。

一旦我们只有重要的空格,我们就可以检测空格/单词和单词/空格的边界并使用切片提取所有单词。

def mysplit(html):
    in_tag = False
    in_word = False
    for i, ch in enumerate(html):
        if ch == '<':
            in_tag = True
        elif ch == '>':
            in_tag = False
        space = ch.isspace() and not in_tag
        if not in_word and not space:
            in_word = True
            begin = i
        elif in_word and space:
            in_word = False
            yield html[begin:i]
    if in_word:
        yield html[begin:]

testhtml = 'I like <a class="thing1 thing2">this thing</a>'
print(list(mysplit(testhtml)))
# prints: ['I', 'like', '<a class="thing1 thing2">this', 'thing</a>']

编辑:我对最初发布的代码做了一些小改动,以增加一点可读性。

【讨论】:

  • 我认为这可能会解决我所有的问题...看看我是否可以仅在元素中至少有一个单词的文本时才能将其拆分。
猜你喜欢
  • 2015-12-27
  • 1970-01-01
  • 2015-09-14
  • 1970-01-01
  • 1970-01-01
  • 2021-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多