我正在用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)但没起作用。
是因为我哪里出错了吗?有办法把它们移走吗?
发布于 2015-06-03 21:52:13
我怀疑换行符实际上出现在源HTML文件中。我试图使用您的段落来重现您的错误,直到我在源文件中插入了一个新行之后才得到任何\n。这也解释了为什么其他较长的段落不会发生这种情况:它们只是在html源文件中没有任何实际的换行符。
话虽如此,如果我添加您的re.sub行,我确实会删除换行符。(不过,我在sprt[i][2]上知道,当然不是sprt[i][1] --你在那里找错地方了吗?)
发布于 2015-06-03 21:21:16
sprt[i][2] = re.sub(r"\n", "", sprt[i][1], re.U, re.S)
^^您可以尝试使用raw模式。
https://stackoverflow.com/questions/30630047
复制相似问题