我正在尝试使用 BeautifulSoup 解析来自网络的一些数据。到目前为止,我已经使用以下代码从表中获取了所需的数据:
def webParsing(canvas):
url='http://www.cmu.edu/dining/hours/index.html'
try:
page= urllib.urlopen(url)
except:
print 'Error while opening html file. Please ensure that you',
print ' have a working internet connection.'
return
sourceCode=page.read()
soup=BeautifulSoup(sourceCode)
#heading=soup.html.body.div
tableData=soup.table.tbody
parseTable(canvas,tableData)
def parseTable(canvas,tableData):
canvas.data.hoursOfOperation=dict()
rowTag='tr'
colTag='td'
for row in tableData.find_all(rowTag):
row_text=[]
for item in row.find_all(colTag):
text=item.text.strip()
row_text.append(text)
(locations,hoursOpen)=(row_text[0],row_text[1])
locations=locations.split(',')
for location in locations:
canvas.data.hoursOfOperation[location]=hoursOpen
print canvas.data.hoursOfOperation
如您所见,第一列中的“项目”使用字典映射到第二列中的项目。数据在打印时几乎完全符合我的要求,但是在 python 中,这些字符串中有很多格式,例如 '\n' 或 '\xe9' 或 '\n\xao'。有没有办法删除所有格式?换句话说,删除所有换行符、任何代表特定编码的字符、任何代表重音字符的字符,然后只获取字符串文字?我不需要最有效或最安全的方法,我是初学者,所以最好使用最简单的方法!谢谢!
最佳答案
这里有一个技巧:您可以将其编码为 ascii
,然后删除所有其余部分:
>>> 'abc\xe9'.encode('ascii', errors='ignore')
b'abc'
编辑:
啊,我忘了你也不想要标准的特殊字符。改用这个:
''.join(s for s in string if ord(s)>31 and ord(s)<126)
希望这对您有所帮助!
关于python - 从字符串中删除格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20183669/