【问题标题】:Python string processing, Unicode & Beautiful SoupPython 字符串处理、Unicode & Beautiful Soup
【发布时间】:2011-02-23 08:26:26
【问题描述】:

我一直在寻找一个错误的解决方案,但我还没有找到/理解一个可行的方案。本质上,如果我使用字符串函数(翻译、剥离等),我会收到 Unicode 错误(ascii'编解码器无法在位置 y:ordinal not in range(128) 编码字符'x'。但是当我尝试 Beautiful Soup处理文本,我没有遇到 Unicode 错误,但难度(我应该说不熟悉)对我来说相当高。这是我的代码摘录:

...

import urllib2,sys
import re
import os
import urllib
import string
import time
from BeautifulSoup import BeautifulSoup,NavigableString, SoupStrainer
from string import maketrans
import codecs

trantab=string.maketrans(",",";") 
...

                html5 = urllib2.urlopen(address5).read()
                time.sleep(1.5)

                soup5 = BeautifulSoup(html5)

                for company in iter(soup5.findAll(height="20px")):
                    stream = ""
                    count_detail = 1
                    for tag in iter(company.findAll('td')):
                        if count_detail > 1:
                            stream = stream + string.translate(str(tag.text),trantab)
                            if count_detail < 4 :
                                stream=stream+","
                        count_detail = count_detail + 1
                    print str(storenum)+","+branch_name_address+","+ stream

....

这个脚本运行了一段时间,然后在stream = stream + string.translate(str(tag.text),trantab)轰炸

基本上,我只是想在我正在处理的字段中用分号替换逗号。

另外,尝试使用 string.strip 删除嵌入的空白/空白,但我遇到了类似的错误。

我将如何使用 Beautiful soup 做同样的事情(至于用分号替换逗号并删除空格)?

如果我只使用字符串函数,是否有代码可以解决那些讨厌的 Unicode 错误?

【问题讨论】:

    标签: python string unicode beautifulsoup


    【解决方案1】:

    您将str 对象与unicode 对象混合在一起,这会导致Python 解释器将一个对象强制转换为另一个对象。字符串/Unicode 强制转换需要编码,默认情况下假定为 ascii。如果这个假设不成立,就会出现这种错误。

    一般的解决方案是不要将strunicode 混合使用:尽可能使用unicode,并使用string.encode('utf8', 'strict')unicode_string.decode('utf8', 'strict') 进行任何显式转换(UTF-8 就是一个示例)。

    在这种情况下,替换

    stream = stream + string.translate(str(tag.text),trantab)
    

    stream = stream + tag.text.replace(u',', u';')
    

    【讨论】:

      猜你喜欢
      • 2016-08-02
      • 1970-01-01
      • 2017-06-29
      • 2023-03-30
      • 2022-07-16
      • 2019-09-04
      • 2018-09-29
      • 2011-02-07
      • 1970-01-01
      相关资源
      最近更新 更多