python2.6中特殊字符的使用

2024-03-29 11:27:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有点累了,但这里是:

我用python2.6.5在ubuntubox上用beauthoulsoap进行tome HTML抓取

python2.6.5的原因:BeautifulSoap在3.1版本下很糟糕

我尝试运行以下代码:

# dataretriveal from html files from DETHERM
# -*- coding: utf-8 -*-

import sys,os,re,csv
from BeautifulSoup import BeautifulSoup


sys.path.insert(0, os.getcwd())

raw_data = open('download.php.html','r')
soup = BeautifulSoup(raw_data)

for numdiv in soup.findAll('div', {"id" : "sec"}):
    currenttable = numdiv.find('table',{"class" : "data"})
    if currenttable:
        numrow=0
        numcol=0
        data_list=[]
        for row in currenttable.findAll('td', {"class" : "dataHead"}):
            numrow=numrow+1
        for ncol in currenttable.findAll('th', {"class" : "dataHead"}):
            numcol=numcol+1
        for col in currenttable.findAll('td'):
            col2 = ''.join(col.findAll(text=True))
        if col2.index('±'):
        col2=col2[:col2.index('±')]
            print(col2.encode("utf-8"))
        ref=numdiv.find('a')
        niceref=''.join(ref.findAll(text=True))

现在,由于±符号,我在尝试将代码与

Python代码.py在

回溯(最近一次呼叫): 文件“detherm-测试时间“,第25行,英寸 如果列2.索引('±'): UnicodeDecodeError:“ascii”编解码器无法解码位置0中的字节0xc2:序号不在范围内(128)

我怎么解决这个问题?输入u,则得到:'''->;u''''结果为:

回溯(最近一次呼叫): 文件“detherm-测试时间“,第25行,英寸 如果col2.索引(u'±'): 值错误:找不到子字符串

当前代码文件编码为utf-8

谢谢你


Tags: 文件代码infromfordatautfclass
1条回答
网友
1楼 · 发布于 2024-03-29 11:27:18

"±"(在python2.x中)这样的字节字符串是在源文件的编码中编码的,这可能不是您想要的。如果col2真的是一个Unicode对象,那么您应该使用u"±",就像您已经尝试过的那样。您可能知道,somestring.index如果找不到出现的情况,而somestring.find返回-1,则会引发异常。因此,这

    if col2.index('±'):
        col2=col2[:col2.index('±')] # this is not indented correctly in the question BTW
        print(col2.encode("utf-8"))

应该是

^{pr2}$

如果这不是一个例外。在

相关问题 更多 >