从字符串中删除格式

时间:2013-11-25 01:57:44

标签: python parsing web encoding formatting

我正在尝试使用BeautifulSoup从Web解析一些数据。到目前为止,我已经使用以下代码从表中获取了所需的数据:

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'。有没有办法删除所有格式?换句话说,删除所有换行符,表示特定编码的任何内容,表示重音字符的任何内容,并获取字符串文字?我不需要最有效或最安全的方法,我是一名初学程序员,所以最好用最简单的方法表示赞赏!谢谢!

2 个答案:

答案 0 :(得分:4)

这是一个技巧:您可以将其编码为ascii,并删除所有其余内容:

>>> 'abc\xe9'.encode('ascii', errors='ignore')
b'abc'

修改

啊,我忘了你也不想要标准的特殊字符。请改用:

''.join(s for s in string if ord(s)>31 and ord(s)<126)

希望这有帮助!

答案 1 :(得分:1)

从这个question你可以尝试这样的事情:

def removeNonAscii(s): return "".join(i for i in s if ord(i)<126 and ord(i)>31)