【问题标题】:Removing newlines (\n) with BeautifulSoup使用 BeautifulSoup 删除换行符 (\n)
【发布时间】:2015-06-03 20:28:41
【问题描述】:

我正在用 BS4 解析 HTML 页面:

import re
import codecs
import MySQLdb
from bs4 import BeautifulSoup

soup = BeautifulSoup(open("sprt.htm"), from_encoding='utf-8')
sprt = [[0 for x in range(3)] for x in range(300)]
i = 0

for para in soup.find_all('p'):
    if para.strong is not None:
        sprt[i][0] = para.strong.get_text()
        sprt[i][1] = para.get_text()
        sprt[i][1] = re.sub(re.escape(sprt[i][0]), "", sprt[i][1], re.UNICODE)
        sprt[i][2] = sprt[i][1]
        sprt[i][2] = re.sub(r".+[\.\?][\s\S\n]", "", sprt[i][1], re.S)
        sprt[i][2] = re.sub(r".+Panel", "Panel", sprt[i][2], re.S)
        sprt[i][1] = re.sub(re.escape(sprt[i][2]), "", sprt[i][1])

i += 1
x = 0

我正在解析的页面充满了类似 3 的段落:

<p><strong>Name name. </strong>The Visual Politics of Play: On The Signifying Practices of Digital Games. Panel Proposal (2p)</p>
<p><strong>Name name and Name name. </strong>Pain, Art and Communication. Panel Proposal (2p)</p>
<p><strong>Name name, Name name and Name name. </strong>Waves of Technology: The Hidden Ideologies of Cognitive Neuroscience and the future production of the Iconic. Panel Proposal (2p)</p>

解析工作正常,直到最后一段:

<p><strong>Name name, Name name and Name name. </strong>Waves of Technology: The Hidden Ideologies of Cognitive Neuroscience and the future production of the Iconic. Panel Proposal (2p)</p>

我在数组的最后一个槽中找到的是这样的:

[u'Name name, Name name\xa0and Name name.\xa0', u'Waves\n of Technology: The Hidden Ideologies of Cognitive Neuroscience and the \nfuture production of the Iconic.\xa0Panel Proposal (2p)', u'Waves\n of Technology: The Hidden Ideologies of Cognitive Neuroscience and the \nfuture production of the Iconic.\xa0Panel Proposal (2p)']

有两个换行符 (\n) 出现在奇怪的地方(Waves 之后和 future 之前)。它们总是出现在相同的位置,而不是随机出现。 我以为是因为段落过长,但有些较长的段落没有出现\n

我试图删除它们:

sprt[i][2] = re.sub("\n", "", sprt[i][1], re.U, re.S)

但它没有用。

换行是因为我在某处犯了错误吗?有没有办法去除它们?

【问题讨论】:

  • 它们是字面意思\n 吗?
  • 不,当我从终端复制过去到记事本++时,如果我搜索“\n”我什么都没有,我猜这是一个特殊的“\”。如果我打印 sprt[][thelastline],我有类似的东西:Waves [NEWLINE] of Technology: The Hidden Ideologies of Cognitive Neuroscience and the [NEWLINE] the Hidden Ideologies of the Iconic.\xa0Panel Proposal (2)

标签: python regex bs4


【解决方案1】:

我怀疑换行符实际上出现在源 Html 文件中。我尝试使用您的段落重现您的错误,但直到我在源文件中实际插入新行之前,我没有得到任何 \n。这也可以解释为什么其他较长的段落不会发生这种情况:它们在 html 源文件中根本没有任何实际的换行符。

话虽如此,如果我添加您的 re.sub 行,我确实会删除换行符。 (我在sprt[i][2] 中得到了这个,当然不是sprt[i][1] - 你有没有可能在那里找错地方了?)

【讨论】:

  • 我从 html 源文件中复制/粘贴了 3 段。你说的对。我找错地方了……re.sub 行工作正常,现在解析完美。对不起,这是我的错。 (我还是不明白他们是从哪里来的)
【解决方案2】:
sprt[i][2] = re.sub(r"\n", "", sprt[i][1], re.U, re.S)

                   ^^

你可以试试raw模式。

【讨论】:

  • 即使使用“原始”模式也不受影响
  • 因为我找错地方了......它正在与raw合作
猜你喜欢
  • 2012-08-12
  • 2021-02-14
  • 1970-01-01
  • 1970-01-01
  • 2015-04-24
  • 1970-01-01
  • 2020-09-25
  • 2016-07-13
  • 1970-01-01
相关资源
最近更新 更多